var ordersApp = angular.module('JxApp', ['services','JxApp.menu','ui.bootstrap.datepicker',"ui.bootstrap.tpls",'JxApp.mulsel','ai.progress', 'ai.Grid','mgcrea.ngStrap','ngAnimate',"ng-currency","ipCookie",'angularFileUpload']);

var maxRowId ;// 当前最大的行号

ordersApp.directive('compileHtml', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
            scope.$watch(function () {return scope.$eval(attrs.ngBindHtml);},
                function(html) {
                    ele.html(html);
                    $compile(ele.contents())(scope);
                });
        }
    };
});

ordersApp.controller("OrderModule",function($scope,$filter,httpServices,ipCookie,$filter,$upload){

	/**
	 * 初始化单据信息
	 */
	$scope.resources = RESOURCES; //权限资源
	var isReadonly = RESOURCES.indexOf('purchaseOrderSaveDraft') == -1 && RESOURCES.indexOf('approvalConfirmPurchase') == -1 && RESOURCES.indexOf('purchaseOrderDelete') == -1 && RESOURCES.indexOf('purchaseOrderDestroy') == -1; //是否只有只读权限
	$scope.isReadonly = isReadonly;
	$scope.allAccount = allAccount;
	$scope.loadingTips = "加载中...";
	$scope.selMaxDate = Date();
	$scope.selMinDate = new Date((new Date()).getTime()-90 * 24 * 3600 * 1000);
	removeByKey(allAccountItem,'id',10);//特殊账目类型“账户互转”不可选择
	removeByKey(allAccountItem,'id',1);//特殊账目类型“期初调整”不可选择
	removeByKey(allAccountItem,'id',5);//特殊账目类型“优惠金额”不可选择
	removeByKey(allAccountItem,'id',6);//特殊账目类型“充值”不可选择
	removeByKey(allAccountItem,'id',7);//特殊账目类型“分销”不可选择
	$scope.allAccountItem = $filter('filter')(allAccountItem,{isEnable:1});
	setConfig(httpServices,'orderList.manualAddNumber',$scope,'manualAddNumber',false);
	$scope.changeManualAddNumber = function(){
		$scope.manualAddNumber = !$scope.manualAddNumber;
		saveConfig(httpServices,'orderList.manualAddNumber',$scope.manualAddNumber);
	};
	$scope.businessConfig = {zeroPaid:1};
	setConfig(httpServices,"businessConfig",$scope,"businessConfig",$scope.businessConfig);
	$scope.imgList = [];
	
	$scope.isOpenWoutOrWinStore = isOpenWoutOrWinStore();
    $scope.snPacketArr = [];
    $scope.packetNumberDisabled = false;
    
    $scope.lastSupplierPrices = []; //保留客户价格信息数组
	
	$scope.businessConfig = {zeroPaid:1,defaultLastPrice:2,defaultSupplierLastPrice:2};
	setConfig(httpServices,"businessConfig",$scope,"businessConfig",$scope.businessConfig);
	
	//是否开启自动选择上次价格，如果不开启则有上次价格时只显示在下拉框供参考，不自动选择上次价格
	$scope.autoChoseLastPriceEnable = $scope.businessConfig.defaultSupplierLastPrice==1?true:false;
	
	/**
	 * 获取该商品计算后的相关属性
	 */
	$scope.getGoodPropertyAfterCalc = function(good) {
    	var priceTemp = setScale(good['price'], 2);
		var factoryPriceTemp = '';
    	var supplierPriceTemp = ''; 
    	var supplierTruePriceTemp = ''; 
    	var priceTempObject = getObjectByObject($scope.lastSupplierPrices,{goodsSn:good.goodsSn,colorId:parseInt(good.colorId),sizeId:parseInt(good.sizeId)});
    	if(priceTempObject){
    		factoryPriceTemp = (priceTempObject.factoryPrice || priceTempObject.factoryPrice === 0)? setScale(priceTempObject.factoryPrice, 2):'';
    		supplierPriceTemp = (priceTempObject.supplierPrice || priceTempObject.supplierPrice === 0)?setScale(priceTempObject.supplierPrice, 2):'';
    		supplierTruePriceTemp = (priceTempObject.supplierTruePrice || priceTempObject.supplierTruePrice === 0)?setScale(priceTempObject.supplierTruePrice, 2):'';
    	}else{
    		priceTempObject = getObject($scope.lastSupplierPrices,"goodsSn",good.goodsSn);
    		if(priceTempObject){
    			factoryPriceTemp = (priceTempObject.factoryPrice || priceTempObject.factoryPrice === 0)?setScale(priceTempObject.factoryPrice, 2):'';
    		}
    	}
    	
    	//设置单价,优化级:上次单价>客户分类单价>批发价
    	if((supplierPriceTemp || supplierPriceTemp === 0) && $scope.autoChoseLastPriceEnable){
    		priceTemp = supplierPriceTemp;
    	}else if(factoryPriceTemp || factoryPriceTemp === 0) {
    		priceTemp = factoryPriceTemp;
    	}
    	
    	var truePriceTemp = 0;
    	var discountTemp = 0;
    	var amountTemp = 0;
    	var trueAmountTemp = 0;
    	
    	if((supplierTruePriceTemp || supplierTruePriceTemp === 0) && $scope.autoChoseLastPriceEnable){  //如果有上次折后价，则本次折后价也按上次折后价来
    		if(priceTemp === 0){ //如果上次价格为0，则折后价也为0，折扣为100%
    			truePriceTemp = 0;
				discountTemp = 100;
				amountTemp = 0;
				trueAmountTemp = 0;
    		}else{
    			truePriceTemp = supplierTruePriceTemp;
				discountTemp = setScale(accMul(accDiv(supplierTruePriceTemp,priceTemp),100),2);
				amountTemp = accMul(priceTemp, good.quantity);
				trueAmountTemp = accMul(supplierTruePriceTemp,good.quantity);
    		}
    	} else {
    		truePriceTemp = setScale(accDiv(accMul(priceTemp,$scope.supplierDiscount),100),2);
    		discountTemp = $scope.supplierDiscount;
    		amountTemp = accMul(priceTemp, good.quantity);
    		trueAmountTemp =  accMul(good.quantity,setScale(accDiv(accMul(priceTemp,$scope.supplierDiscount),100),2));
    	}
    	
    	return {
    		supplierPriceTemp: supplierPriceTemp,
    		supplierTruePriceTemp: supplierTruePriceTemp,
    		factoryPriceTemp: factoryPriceTemp,
    		priceTemp: priceTemp,
    		truePriceTemp: truePriceTemp,
    		discountTemp: discountTemp,
    		amountTemp: amountTemp,
    		trueAmountTemp: trueAmountTemp
    	}
	}
	
	/**
	 * 更新列表中的折扣
	 */
	$scope.updateDiscount = function(){
		
		var allRowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
		
		var goodsSnArr = [];
		for(var i = 0;i < allRowData.length;i++){
			if(allRowData[i]['goodsSn']){
				goodsSnArr.push(allRowData[i]['goodsSn']);
			}
		}
		
		//需要有供应商
		if($scope.order.supplier.val){
			httpServices.post(base + '/admin/inner/supplier/getSupplierWithPrices.ac',$.param({id:$scope.order.supplier.val,goodsSnArr:goodsSnArr}),{
	            headers:
	            {
	                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
	            }
	        }).success(function(result) {
	        	if(result.statusCode == 1) {
	        		$scope.supplierDiscount = (result.object.objSupplier && result.object.objSupplier.discount)?result.object.objSupplier.discount:100;
	        		var rowIds = jQuery("#list4").jqGrid('getDataIDs'); //获取所有行Id
	        		$scope.lastSupplierPrices = result.object.goodsPricesList;
	                for (var i = 0; i < rowIds.length; i++) {
	                	var thisRow = $("#list4").jqGrid("getRowData",rowIds[i]); //当前行数据
	                	var property = $scope.getGoodPropertyAfterCalc(thisRow);
	                	
	                	$("#list4").setRowData(rowIds[i], {
	                		supplierPrice: property.supplierPriceTemp,
	                		supplierTruePrice: property.supplierTruePriceTemp,
	                		factoryPrice: property.factoryPriceTemp,
	                		price: property.priceTemp,
	                		truePrice: property.truePriceTemp, 
	                		discount: property.discountTemp, 
	                		amount: property.amountTemp,
	                		trueAmount: property.trueAmountTemp
	                	});
	                }
	                //更新合计行上的合计指标
	    	        updateTotalNumbers();
		    	        
	    	        setTimeout(function(){	
	      				 $scope.$apply(function(scope){
	      					if(scope.businessConfig.zeroPaid == 1){
	      						scope.order.alreadyPaid = 0;
	      					}else{
	      						scope.order.alreadyPaid = scope.order.finalTotalAmount;
	      					}
	      		    	});
	      			 });
                }
	        });
		}
	};
	
   $scope.updateFinalTotalAmount = function(){
	   
    	$scope.order.finalTotalAmount =accAdd(accSub($scope.order.trueTotalAmount, $scope.order.wipeZero) , $scope.order.otherCost);;
    	if($scope.businessConfig.zeroPaid == 1){
			$scope.order.alreadyPaid = 0;
		}else{
			$scope.order.alreadyPaid = $scope.order.finalTotalAmount;
		}
    };
	
	$scope.initOrder = function()
	{
		$scope.order = {alreadyPaid:0,discount : 100,totalAmount:0,finalTotalAmount:0,wipeZero:0,otherCost:0,handlerName:userLoginInfoJSON.userVO.realName,state:1,itemType:1,businessTime:new Date()};
		function accountCallback(configValue){
			var account = getObject($scope.allAccount,'id',configValue);
			if(account){
				$scope.order.accountId = account.id;
			}
		}
	    if($scope.allAccount[0]){ //账户默认选择第一个
			$scope.order.accountId = $scope.allAccount[0].id;
			if(!onLoadOrdersSn){
				setConfig(httpServices,"purchaseList.accountId",null,null,$scope.allAccount[0].id,accountCallback);
			}
		}
		function supplierCallback(configValue){
			httpServices.post(base + '/admin/inner/supplier/supplierSelectJSON.ac?showDisable=1&id='+configValue.val).success(function(result) {
				
				if(result.optionList.length > 0)
				{
					$scope.order.supplier = result.optionList[0];
					$scope.order.supplier.val = result.optionList[0].id;
					$scope.order.supplierId = result.optionList[0].id;
				}else{
					$scope.order.supplier = firstPageSupplierJson[0];
					$scope.order.supplier.val = firstPageSupplierJson[0].id;
					$scope.order.supplierId = firstPageSupplierJson[0].id;
				}
				$scope.updateDiscount(); //初始化默认折扣
			}).error(function(data,status ){
				$scope.order.supplier = firstPageSupplierJson[0];
				$scope.order.supplier.val = firstPageSupplierJson[0].id;
				$scope.order.supplierId = firstPageSupplierJson[0].id;
				$scope.updateDiscount(); //初始化默认折扣
		    });
			
		}
	    if(firstPageSupplierJson[0]){ //客户默认选择第一个
			$scope.order.supplier = firstPageSupplierJson[0];
			$scope.order.supplier.val = firstPageSupplierJson[0].id;
			$scope.order.supplierId = firstPageSupplierJson[0].id;
			if(!onLoadOrdersSn){
				setConfig(httpServices,"purchaseList.supplier",null,null,firstPageSupplierJson[0],supplierCallback);
			}
		}
	    
	    
	    function storehouseCallback(configValue){
	    	configValue = getObject(allStorehouse,'val',configValue.val);
			if(configValue){
				$scope.order.depot = configValue;
				$scope.order.depotId = configValue.val;
			}
		}
		if(allStorehouse[0]){ //仓库默认选择第一个
			$scope.order.depot = allStorehouse[0];
			$scope.order.depotId = allStorehouse[0].val;
			if(!onLoadOrdersSn){
				setConfig(httpServices,"purchaseList.depot",null,null,allStorehouse[0],storehouseCallback);
			}
		}
		
		function otherAccountItemCallback(configValue){
			var accountItem = getObject($scope.allAccountItem, 'id',configValue);
			
			if(accountItem){
				$scope.order.otherAccountItem = configValue;
			}
		}
		if(!onLoadOrdersSn){
			setConfig(httpServices,"purchaseList.otherAccountItem",null,null,null,otherAccountItemCallback);
		}
		
		//判断是否有符合条件的结算账户或者仓库
		if(allAccount.length==0){
			alert("您所在门店暂无可用结算账户，请在结算账户里边添加后再开单！");
		}
		if(allStorehouse.length==0){
			alert("您所在门店暂无归属仓库，请在仓库管理里边添加后再开单！");
		}
	};
	
	$scope.initOrder();
	
	//********************************************************************
	//左侧列表
	//********************************************************************

    /**
     * 列表点击事件    此函数要放在表格定义之前
     */
    $scope.clickList = function(id)
	{
    	var gridRow = $(this).jqGrid("getRowData",id);  //取出行数据
    	$scope.loadOneOrder(gridRow.purchaseSn);  //加载订单到右边
	};
	
	$scope.searchModel = {state:12,createTimeBegin:getOffsetDayBegin(new Date(),-29),createTimeEnd:new Date(),supplier:'',purchaseSn:''};
	$scope.showSearchTab = true;
	//订单状态
	$scope.states = [
	    {val:1,text:"草稿",css:GL_CONS.STATE_ICON_CSS.draft},
	    {val:2,text:"已采购",css:GL_CONS.STATE_ICON_CSS.receive},
	    {val:4,text:"待入库",css:GL_CONS.STATE_ICON_CSS.winStore},
	    {val:5,text:"部分入库",css:GL_CONS.STATE_ICON_CSS.someInStore},
	    {val:9,text:"已撤销",css:GL_CONS.STATE_ICON_CSS.destroy}
	];
	
	//订单状态格式化显示
	$scope.formatState = function(val, opt, row)
	{
	    return stateFormat($scope.states, val);
	};
	
	//格式化jqgrid提交数据
	$scope.getPostParam = function(){
		return angular.fromJson({
			'state' : $scope.searchModel.state,
			'createTimeBegin' : transferGMTStringtoBJTime(getDayBeginStr($scope.searchModel.createTimeBegin)),
			'createTimeEnd' : transferGMTStringtoBJTime(getOffsetDayBeginStr($scope.searchModel.createTimeEnd,1)),
			'supplierId' : $scope.searchModel.supplierId,
			'purchaseSn' : $scope.searchModel.purchaseSn
		});	
	};
	
    //列表格配置
    $scope.gridSettings = {
    	cmTemplate:{sortable:false},
        datatype: "json",
        url: base + '/admin/inner/orders/purchase/purchaseListJSON.ac?itemType=1',
        postData : $scope.getPostParam(),
        colModel: [
            {
            	 hidden: true,
                name: 'purchaseSn',
                index: 'purchaseSn',
                align : 'center',
                label: '单号'
            },{
			    name: 'state',
			    index: 'state',
			    width: 45,
			    align : 'center',
			    formatter:$scope.formatState,
			    label: '状态'
			},{
            	name: 'businessTime',
                index: 'businessTime',
                width: 105,
                align : 'center',
                label: '日期',
                formatter:timeFormat
            },{
                name: 'supplierName',
                index: 'supplierName',
                align : 'center',
                label: '供应商名称'
            }
            
        ],
        onCellSelect: $scope.clickList, 
        loadComplete: function(){disableTarget($scope.target,false);},
        loadError : function() {disableTarget($scope.target,false);},
        pager: "#pager2", //        --得到分页的层
        rownumbers: false, //	--是否在表格最前端添加1列为自动编号
        rowNum: 18, //       --一页显示几行？
        page: 1, //    --从弟几页开始
        rowlist: [ 10, 20, 30 ], //    --多少页一段
        height:"100%",
        autowidth:true,
        shrinkToFit:true,
        navGrid: {
            refresh: false,
            add: false,
            edit: false,
            del: false,
            search: false,
            sortable: false
            // (3) 点击删除按钮，则调用openDialog4Deleting方法
        }
    };
    
	
	/**
     * 查询列表数据函数
     */
    $scope.searchTrigger = function()
	{
		$scope.showSearchTab = !$scope.showSearchTab;
	};
    
	$scope.searchList = function()
	{
		if($scope.searchModel.createTimeEnd &&$scope.searchModel.createTimeBegin > $scope.searchModel.createTimeEnd){
			alert("起始日期不能比结束日期大，请您重新调整查询日期之后再查询！");
			return;
		}
		//取消上个button禁用
		disableTarget($scope.target,false,true);
		$scope.target = getEvtTarget();
		disableTarget($scope.target,true);
    	$scope.listGrid.jqGrid("setGridParam",{postData:null});
		$scope.listGrid.jqGrid("setGridParam", {   
		        url: base + '/admin/inner/orders/purchase/purchaseListJSON.ac?itemType=1',   
		        page: 1,
		        postData:$scope.getPostParam() //发送数据 
		 }).trigger('reloadGrid');
	};
	
	//********************************************************************
	//左侧列表end
	//********************************************************************
	
	$scope.loaddingMsg = "加载中...";
	
	//订单进度条
    $scope.progressData =
    {
        currentStep: 0,
        stepTexts: [
            "草稿",
            "已采购"
            
        ]
    };
	
    $scope.goods = []  ;
    $scope.order.ordersSn ='';
	
    /**
     * 查询供应商信息,并更新供应商欠款
     */
	$scope.getSupplierInfo  = function()
	{
		
		httpServices.post(base + '/admin/inner/supplier/supplierGetFromPurchase.ac?id='+$scope.order.supplier.val).success(function(result) {
			
			if(!result.objSupplier || !result.objSupplier.balance)
			{
				$scope.banlanceSupplier = {banlance:0};
			}
			else
			{
				$scope.banlanceSupplier = {banlance:result.objSupplier.balance};
			}
			$scope.supplierDiscount = result.objSupplier.discount;
		});
	};
	
	
	/**
	 * 供应商变化数据
	 */
	$scope.$watch('order.supplier.val', function(){
		if($scope.order.supplier && $scope.order.supplier.val)
		{
			$scope.getSupplierInfo();
			
		}
    });
	
	/**手工点选供应商后按默认折扣更新商品折扣**/
	$scope.supplierSelectChangeFun = function(){
		var supplier = {id:$scope.order.supplier.id,text:$scope.order.supplier.text,discount:$scope.order.supplier.discount,val:$scope.order.supplier.id};
		saveConfig(httpServices,'purchaseList.supplier',supplier,GL_CONS.USER_CONFIG_DEVICE.common);
		$scope.updateDiscount();
	};
	$scope.depotSelectChangeFun = function(){
		var depot = {val:$scope.order.depot.val,text:$scope.order.depot.text};
		saveConfig(httpServices,'purchaseList.depot',depot,GL_CONS.USER_CONFIG_DEVICE.common);
	};
	$scope.accountSelectChangeFun = function(){
		saveConfig(httpServices,'purchaseList.accountId',$scope.order.accountId,GL_CONS.USER_CONFIG_DEVICE.common);
	};
	$scope.otherAccountItemSelectChangeFun = function(){
		saveConfig(httpServices,'purchaseList.otherAccountItem',$scope.order.otherAccountItem,GL_CONS.USER_CONFIG_DEVICE.common);
	};
	/**
     * 监视仓库选择框选择框，以便更新商品明细表中的当前库存
     */
	$scope.$watch('order.depotId', function(){
		$scope.setGoodsStoredCount();
	});
	
	/*刷新商品明细表中各个商品的当前库存数量*/
	$scope.setGoodsStoredCount = function(){
		if($scope.order.depotId == null || $scope.order.depotId == undefined){
			return ;
		}
		
		var rowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
		
		var goodsList = [];
		
		for(var i = 0; i < rowData.length;i++){
			if(rowData[i]['goodsSn'] != null && rowData[i]['goodsSn'] != "" &&
			   rowData[i]['colorId'] != null &&  rowData[i]['colorId'] != "" &&
			   rowData[i]['sizeId'] != null &&  rowData[i]['sizeId'] != ""){
			goodsList.push({storehouseId:$scope.order.depotId,goodsSn:rowData[i]['goodsSn'],colorId:rowData[i]['colorId'],sizeId:rowData[i]['sizeId']});
			}
		}
		
		if(goodsList.length == 0){
			return ;
		}
		
		
		//提交后台获取各个商品对应的库存
		httpServices.post(base + '/admin/inner/storehouse/getGoodsListStoredCount.ac',$.param({goodsList:angular.toJson(goodsList)}),{
            headers:
            {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function(result) {
        	
        	var rowIds = jQuery("#list4").jqGrid('getDataIDs'); //获取所有行Id
        	var countTemp = 0;
        	for(var i = 0; i < rowIds.length;i++){
        		var thisRow = $("#list4").jqGrid("getRowData",rowIds[i]); //获取第i行的数据
        		countTemp = getObject(result,"serialNo",$scope.order.depotId+'-'+thisRow['goodsSn']+'-'+thisRow['colorId']+'-'+thisRow['sizeId']);
        		if(countTemp == null || countTemp==undefined){
        			$("#list4").setRowData(rowIds[i], { number : 0 });
        		}else{
        			$("#list4").setRowData(rowIds[i], { number : countTemp.number });
        		}
        	}
        	
		});
		
	};
	
	
	
    /**
     * 获取全部尺码数据
     */
	$scope.initSizeList = function()
	{
		//全部尺码数据
	    $scope.allSizes = [];
		httpServices.post(base + '/admin/inner/goods/size/allSizeListJSON.ac').success(function(result) {
			$scope.allSizes = result.rows;  //所有分组数据
		});
	};
	$scope.initSizeList(); //获取全部尺码数据
    
	
	/**
     * 获取全部颜色数据
     */
	$scope.initColorList = function()
	{
		//全部颜色数据
	    $scope.initColorList = [];
		httpServices.post(base + '/admin/inner/goods/color/allColorListJSON.ac').success(function(result) {
			$scope.allColors = result.rows;  //所有分组数据
		});
	};
	$scope.initColorList(); //获取全部尺码数据
    
    //当前商品包含的尺码数据
    $scope.currentSizes = [];

    /**
     * 处理并显示二维录入框
     */
    $scope.showAndProTwoDimensionSel = function(currentRowData)
    {
    	$scope.currentSizes = [];   //当前商品所拥有的尺码
    	$scope.currentColors = []; //当前商品所拥有的颜色

        var curGoodSn = currentRowData['goodsSn']; //行货号
        var curGoodName = currentRowData['name']; //商品名称
        if(curGoodSn == undefined || curGoodSn == "")
        {
            return false;
        }
       
        //为了不保留原来的输入数据，这里重新申请了空间。
        $scope.currentSizes =  $filter('filter')(angular.copy(idStringToObjectArray($scope.allSizes, currentRowData['sizeIds'], 'id', ',')),{
        	status:1
        });
        $scope.currentColors = $filter('filter')(angular.copy(idStringToObjectArray($scope.allColors, currentRowData['colorIds'], 'id', ',')),{
        	status:1
        });
        
        if($scope.currentSizes.length == 0){
        	$scope.warningMsg = '商品 【' + curGoodSn + ' ' + curGoodName + '】没有可用的尺码！';
    		showAlert();
        	return false;
        }
        if($scope.currentColors.length == 0){
        	$scope.warningMsg = '商品 【' + curGoodSn + ' ' + curGoodName + '】没有可用的颜色！';
    		showAlert();
        	return false;
        }
        
        
        $scope.selIndexX = 0; //二维录入中，横向选中下标
        $scope.selIndexY = 0; //二维录入中，竖向选中下标
        $("#goods"+$scope.selIndexY+"_"+$scope.selIndexX).focus();
        
        $scope.showTwoDimension = true;
        $( "#twoDisDiv" ).dialog({ title: currentRowData.name+" "+currentRowData.goodsSn,dialogClass: 'twoDisDiv'});

        $scope.updateSupplierPrice($scope.order.supplierId, [curGoodSn], function(result) {
        	$scope.getOneGoodSupplierPrices(result, {goodsSn:curGoodSn});
        	$( "#twoDisDiv" ).dialog( "open" );
        });
        $scope.getStoredCount(curGoodSn);
        
        $("#list4").jqGrid("saveCell",lastrow,lastcell);
        
        return true;
    };
    
    /* 二维录入框批量设置所有数量*/
    $scope.allNumberBatchSet = function(){
    	for(var i=0;i<$scope.currentColors.length;i++){
    		for(var j=0;j<$scope.currentSizes.length;j++){
    			$scope.currentColors[i][$scope.currentSizes[j].id] = $scope.twoDisTableSetNumber;
        	}
    	}
    	$scope.twoDisTableSetNumber = '';
		$scope.allNumberBatchSetting = false; 
		$("#twoDisConfirmBtn").focus();
    };
    
    /* 二维录入框批量设置某一颜色的所有数量*/
    $scope.colorNumberBatchSet = function(){
    	var colorIndex = $scope.currentSettingId;
    	for(var i=0;i<$scope.currentSizes.length;i++){
    		$scope.currentColors[colorIndex][$scope.currentSizes[i].id] = $scope.twoDisTableSetNumber;
    	}
    	$scope.twoDisTableSetNumber = '';
    	$scope.currentSettingId = '';
		$scope.colorNumberBatchSetting = false; 
		$("#twoDisConfirmBtn").focus();
    };
    
    /* 二维录入框批量设置某一尺码的所有数量*/
    $scope.sizeNumberBatchSet = function(sizeId){
    	var sizeId = $scope.currentSettingId;
    	for(var i=0;i<$scope.currentColors.length;i++){
    		$scope.currentColors[i][sizeId] = $scope.twoDisTableSetNumber;
    	}
    	$scope.twoDisTableSetNumber = '';
    	$scope.currentSettingId = '';
		$scope.sizeNumberBatchSetting = false;
		$("#twoDisConfirmBtn").focus();
    };
    
    /* 二维录入框指设置取消 */
    $scope.numberBatchSetCancel = function(){
    	$scope.twoDisTableSetNumber = '';
    	$scope.allNumberBatchSetting = false;
    	$scope.colorNumberBatchSetting = false;
    	$scope.sizeNumberBatchSetting = false;
    	$("#twoDisConfirmBtn").focus();
    };
    
    /* 二维录入框点击尺码显示设置数量 */
    $scope.toSetSizeNumber = function(index){
    	$scope.currentSettingId = $scope.currentSizes[index].id;
    	$scope.colorNumberBatchSetting = false;
    	$scope.allNumberBatchSetting = false;
    	$scope.sizeNumberBatchSetting = true;
    	$scope.numberBatchSetTips = "（批量设置尺码“"+ $scope.currentSizes[index].name + "”下所有单品的数量）";
    	setTimeout(function(){
    		$("#twoDisTableSetNumber").focus();
    	});
    };
    /* 二维录入框点击颜色显示设置数量 */
    $scope.toSetColorNumber = function(index){
    	$scope.currentSettingId = index;
    	$scope.sizeNumberBatchSetting = false;
    	$scope.allNumberBatchSetting = false;
    	$scope.colorNumberBatchSetting = true;
    	$scope.numberBatchSetTips = "（批量设置颜色“"+ $scope.currentColors[index].name + "”下所有单品的数量）";
    	setTimeout(function(){
    		$("#twoDisTableSetNumber").focus();
    	});
    };
    /* 二维录入框点击"批量设置所有"显示设置数量 */
    $scope.toSetAllNumber = function(){
    	$scope.allNumberBatchSetting = true;
    	setTimeout(function(){
    		$("#twoDisTableSetNumber").focus();
    	});
    };
    
    /**
     * 查询库存
     */
    $scope.getStoredCount = function(curGoodSn)
    {
    	$scope.storedCount = [];
    	
    	if($scope.order.depot == undefined || $scope.order.depot.val == undefined)
    	{
    		return;
    	}
    	
    	httpServices.post(base + '/admin/inner/storehouse/getGoodsStoredCountInfo.ac?goodsSn='+encodeURIComponent(curGoodSn)+"&storehouseId="+$scope.order.depot.val).success(function(result) {
    		for(var i=0; i<result.length; i++)
    		{
    			var stored = result[i];
    			if( $scope.storedCount[stored.colorId] == undefined)
    			{
    				$scope.storedCount[stored.colorId] = [];
    			}
    			$scope.storedCount[stored.colorId][stored.sizeId] = stored.number;
    		}
		});
    };
    
    /**
     * 二维录入确定
     */
    $scope.twoDisConfirm = function()
	{
    	//获取输入的数据
    	var insertModels = [];
    	
		if( $scope.storedCount == undefined)
		{
			$scope.storedCount = [];
		}
    	
    	for(var i=0; i<$scope.currentColors.length; i++)
    	{
    		var color = $scope.currentColors[i];
    		for(var j=0; j<$scope.currentSizes.length; j++)
    		{
    			
    			var size = $scope.currentSizes[j];
    			if(color[size.id] != undefined)
    			{
        			if( $scope.storedCount[$scope.currentColors[i].id] == undefined)
        			{
        				$scope.storedCount[$scope.currentColors[i].id] = [];
        			}
        			
        			$scope.currentRowData.sizeId = size.id;
        			$scope.currentRowData.colorId = color.id;
        			$scope.currentRowData.quantity = accMul(color[size.id], $scope.packetNumber);
        			var property = $scope.getGoodPropertyAfterCalc($scope.currentRowData);
        			
					 var newModel = {
						goodsSn : $scope.currentRowData.goodsSn,
						goodName : $scope.currentRowData.name,
						barCode : $scope.currentRowData.barCode,
						name:$scope.currentRowData.name,
						discount :  property.discountTemp,
						sizeId : size.id,
						sizeName : size.name,
						colorId : color.id,
						colorName : color.name,
						quantity : accMul(color[size.id], $scope.packetNumber),
						price : property.priceTemp,
						truePrice: property.truePriceTemp,
						unit : $scope.currentRowData.unit,
						colorIds : $scope.currentRowData.colorIds,
						sizeIds : $scope.currentRowData.sizeIds,
						amount: property.amountTemp,
						trueAmount: property.trueAmountTemp,
						factoryPrice: property.factoryPriceTemp,
						supplierPrice: property.supplierPriceTemp,
						supplierTruePrice: property.supplierTruePriceTemp,
						number : $scope.storedCount[$scope.currentColors[i].id][$scope.currentSizes[j].id],
						packetNumber: $scope.packetNumber,
						packetCount: color[size.id]
					};
					 
    				insertModels.push(newModel);
    				$scope.notSaveOrder = true;
    				if(aboveMaxQuantity(insertModels)){
    				    return;
    				}
    			}
    		}
    	}
    	
    	
    	//把输入的数据插入订单-商品明细表中
    	if(maxRowId == undefined)
	    {
	        maxRowId = jQuery("#list4").jqGrid('getDataIDs').length;
	    }
    	
    	/*判断新增加的单品是否已在列表中存在，如果存在则把新增加单品的数量添加到已存在的记录中*/
    	var sameNumber = 0; //二维录入框中的商品存在于原商品明细表标志（如果存在则合并数量）
    	var notDeleteFlag = false;//二维录入框中的商品与当前编辑行商品一致，则不删除当前行
    	var rowIds = jQuery("#list4").jqGrid('getDataIDs'); 
    	var snPacket = {};
		for(var i=0; i<insertModels.length; i++)
    	{
			
			var existsSameFlag = false;
	        for (var j = 0; j < rowIds.length; j++) {
	        	var thisRow = $("#list4").jqGrid("getRowData",rowIds[j]); 
	        	if(thisRow['goodsSn'] == insertModels[i]['goodsSn'] && thisRow['colorId'] == insertModels[i]['colorId'] && thisRow['sizeId'] == insertModels[i]['sizeId']){
	        		
	        		if(rowIds[j] == $scope.rowId ){//如果是与当前行商品一致，则不合并数量，而是把数量覆盖
	        			$("#list4").setRowData(rowIds[j], {
	        				packetCount :parseInt(insertModels[i]['packetCount']),
	        				packetNumber :parseInt(insertModels[i]['packetNumber']),
							quantity :parseInt(insertModels[i]['quantity']),
							amount :  accMul(parseInt(insertModels[i]['quantity']),thisRow['price']),
							trueAmount: accMul(parseInt(insertModels[i]['quantity']),thisRow['truePrice'])
						});
	        			notDeleteFlag = true;
	        		}else{
	        			if(thisRow['packetNumber'] != insertModels[i]['packetNumber']){
	        				$("#list4").setRowData(rowIds[j], {
	        					packetCount :parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
	        					packetNumber :insertModels[i]['packetNumber'],
	        					quantity : accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity']),
	        					amount : accMul((accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])),thisRow['price']),
	        					trueAmount: accMul((accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])),thisRow['truePrice']) 
	        				});
	        			}else{
	        				$("#list4").setRowData(rowIds[j], {
	        					packetCount :parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
	        					packetNumber :parseInt(insertModels[i]['packetNumber']),
	        					quantity : parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity']),
	        					amount : accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])),thisRow['price']),
	        					trueAmount: accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])),thisRow['truePrice']) 
	        				});
	        			}
	        		}
	        		
	        		existsSameFlag = true;
	        		++sameNumber;
	        		break;
	        	}
	        }
			
	        var spFlag = false;
	        for(var k = 0; k < $scope.snPacketArr.length; k++){
                for(var sp in $scope.snPacketArr[k]){
                    if(sp == insertModels[i]['goodsSn']){
                    	spFlag = true;
                    	break;
                    }
                }
            }
	        if(!spFlag){
	        	//由于开过单的商品下次就只有一个选项，所以此处不需要再判定是否已经有开过此商品
	        	snPacket[insertModels[i]['goodsSn']] = insertModels[i]['packetNumber'];
	        	$scope.snPacketArr.push(snPacket);
	        }
	        
			if(!existsSameFlag){
	    		maxRowId = maxRowId+1;
	    		if(i-sameNumber == 0){
	    			$('#list4').jqGrid('addRowData', maxRowId,insertModels[i],"after",parseInt($scope.rowId));
	    		}else{
	    			$('#list4').jqGrid('addRowData', maxRowId,insertModels[i],"after",maxRowId-1);
	    		}
			 }
    	}	
				
		if(!notDeleteFlag && jQuery("#list4").jqGrid('getDataIDs').length > 1){
			$("#list4").jqGrid("delRowData", $scope.rowId);
		}

		if(jQuery("#list4").jqGrid('getDataIDs').length < 6){
			addNewEmptyRow();
		}
		
		 //更新合计行上的合计指标
        updateTotalNumbers();

        setTimeout(function(){	
				 $scope.$apply(function(scope){
					 if(scope.businessConfig.zeroPaid == 1){
						 scope.order.alreadyPaid = 0;
					 }else{
						 scope.order.alreadyPaid = scope.order.finalTotalAmount;
					 }
		    	});
			 });
		
		var emptyRowId = $scope.getEmptyRowId();
		if(emptyRowId == -1){
			addNewEmptyRow();
			emptyRowId = maxRowId;
		}
		var trs=$("table#list4 tr");
		var index=trs.index($("#list4 tr[id='"+emptyRowId+"']"));
		if($scope.barCodeFocus){
			$scope.barCode = "";
        	$("#barCode").focus();
		}else if(index != -1){
			//var nextRowId =index+1;//下一空白行ID
			setTimeout(function() { $('#list4').editCell(index, 8, true); }, 50); //聚焦下一空白行
		}
    	
    	$( "#twoDisDiv" ).dialog( "close" );
	};
	
	/**
	 * 在列表上变更颜色尺码时更新数据
	 */
	$scope.updateRowDataForChangeSku = function(rowId, good) {
		var property = $scope.getGoodPropertyAfterCalc(good);
		$("#list4").setRowData(rowId, {
    		supplierPrice: property.supplierPriceTemp,
    		supplierTruePrice: property.supplierTruePriceTemp,
    		factoryPrice: property.factoryPriceTemp,
    		price: property.priceTemp,
    		truePrice: property.truePriceTemp, 
    		discount: property.discountTemp, 
    		amount: property.amountTemp,
    		trueAmount: property.trueAmountTemp
    	});
	}
	
	$scope.selIndexX = 0; //二维录入中，横向选中下标
    $scope.selIndexY = 0; //二维录入中，竖向选中下标
    
	/**
     * 在二维录入框中的表格中按下键
     * @param keyEvent
     */
    $scope.pressTable = function(keyEvent)
    {
        var keyCode = keyEvent.which;

        switch(keyCode)
        {
            case 37:  //left
                if($scope.selIndexX>0)
                {
                    $scope.selIndexX--;
                }
                $scope.pressCtrlKeys(keyEvent);
                break;
            case 38: //up
            	if($scope.selIndexY>0)
                {
                    $scope.selIndexY--;
                }
                $scope.pressCtrlKeys(keyEvent);
                break;
            case 39: //right
            	if($scope.selIndexX < $scope.currentSizes.length-1)
                {
            		$scope.selIndexX++;
                }
                
                $scope.pressCtrlKeys(keyEvent);
                break;
            case 40: //down
            	if($scope.selIndexY < $scope.currentColors.length-1)
                {
            		$scope.selIndexY++;
                }
                $scope.pressCtrlKeys(keyEvent);
                break;
            case 13: //Enter
            	stopEvent(keyEvent);
            	$scope.twoDisConfirm();
                break;
            default:

        }

    };

    /**
     * 二维录入框中，对特殊控制键进行处理
     * @param keyEvent
     */
    $scope.pressCtrlKeys = function(keyEvent)
    {
    	stopEvent(keyEvent);
    	$("#goods"+$scope.selIndexY+"_"+$scope.selIndexX).focus();
    	$("#goods"+$scope.selIndexY+"_"+$scope.selIndexX).select();
    };

    /**
     * 二维录入框中，点击输入框
     * @param keyEvent
     */
    $scope.clickInput = function(keyEvent)
    {
        var target = keyEvent.target;
        var targetX = target.getAttribute('indexX');
        var targetY = target.getAttribute('indexY');
        $scope.selIndexX = targetX;
        $scope.selIndexY = targetY;
    };
	
    /**
     * 设置操作按钮可见
     */
    $scope.setOperation = function(noReloadGrid)
    {
    	switch ($scope.order.state) {
		case 1:
		  $scope.progressData =
		    {
		        currentStep: 0,
		        stepTexts: [
		            "草稿",
		            "已采购"
		        ]
		    };
			break;
		case 2:
			$scope.progressData =
		    {
		        currentStep: 1,
		        stepTexts: [
		            "草稿",
		            "已采购"
		        ]
		    };
			break;
		case 4:
			$scope.progressData =
		    {
		        currentStep: 1,
		        stepTexts: [
		            "草稿",
		            "待入库",
		            "部分入库",
		            "已出售"
		        ]
		    };
			break;
		case 5:
			$scope.progressData =
		    {
		        currentStep: 2,
		        stepTexts: [
		            "草稿",
		            "待入库",
		            "部分入库",
		            "已出售"
		        ]
		    };
			break;
		case 9:
			$scope.progressData =
		    {
		        currentStep: 2,
		        stepTexts: [
		            "草稿",
		            "已采购",
		            "已撤销"
		        ]
		    };
			break;
		}
    	
    	//非草稿状态，设为商品明细表只读
        if($scope.order.state !=1 || $scope.isReadonly){		
        	// 移除可编辑样式
        	jQuery("#list4").removeClass('grid-status-edit');	
    		jQuery("#list4").jqGrid('setColProp', 'goodName', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'colorName', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'sizeName', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'quantity', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'packetCount', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'packetNumber', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'discount', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'truePrice', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'price', { editable: false });
    		
    		jQuery("#list4").setGridParam().hideCol("operate");
    		if(!noReloadGrid){
    			jQuery("#list4").trigger("reloadGrid");
    		}
    		
    	}else{
        	// 增加可编辑样式
        	jQuery("#list4").addClass('grid-status-edit');
    		jQuery("#list4").jqGrid('setColProp', 'goodName', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'colorName',{ editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'sizeName', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'quantity', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'packetCount', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'packetNumber', { editable: false });
    		jQuery("#list4").jqGrid('setColProp', 'discount', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'truePrice', { editable: true });
    		jQuery("#list4").jqGrid('setColProp', 'price', { editable: true });
    		
    		jQuery("#list4").setGridParam().showCol("operate");
    		if(!noReloadGrid){
    			jQuery("#list4").trigger("reloadGrid");
    		}
    	};
    };
    $scope.setOperation();
    
    /**
     * 加载商品
     * @param good
     */
    $scope.loadGood = function(inputKey)
    {	
    	$scope.addGoodTip = false;
    	$scope.loaddingMsg = "加载中...";
    	var paramsJson = {searchKey:inputKey};
    	httpServices.post(base+"/admin/inner/goods/goodsSelectForOrder.ac",{},{params:paramsJson}).success(function(data) {
        	$scope.goods = data.optionList;
        	if($scope.goods.length == 0){
        		$scope.addGoodTip = true;
        	}else{
        		$scope.addGoodTip = false;
        		$scope.loaddingMsg = "点击选择";
        	}
      
		}).error(function(e){
			// 错误是聚焦在body上，防止多次触发请求
			$('body').click();
		});
    };
    
    
    /**
     * 商品输入框有变动的时候，加载商品
     * @param good
     */
    $scope.changAutoGoods = function(obj)
    {
    	$scope.goods = []  ;
    	$scope.loadGood( $(obj).val());
    	
    	$scope.rowId = $(obj).parent().parent().parent().attr("id"); //获取当前rowId
    	$scope.curEditGoodInput = $(obj);       //指向当前编辑的表格
    	$scope.showAutoGoods = true;

        var top = (jQuery(obj).offset().top + jQuery(obj).outerHeight())+'px';
        var width = (jQuery(obj).width()+18)+'px';
        var left = (jQuery(obj).offset().left)+'px';
        $scope.autoGoodsStyle =  { top:top , width:width,  left: left};
       
    };
    
    /**
     * 在表格中自动完成输入框中点选商品
     * @param good
     */
    $scope.selAutoGood = function(good)
    {
    	if(aboveMaxQuantity()){
    	    return;
    	}
    	var rowData = $("#list4").jqGrid("getRowData",$scope.rowId);
        if($scope.curEditGoodInput != undefined)
        {

            $scope.curEditGoodInput.val(good.name);
        }
        $scope.selGood = good;
        $scope.showAutoGoods = false;
      //准备弹出二维录入框
        $scope.currentRowData = {
			unit : good.unit,
			quantity : 1,
			price : good.factoryPrice,
			amount : good.factoryPrice,
			sizeIds : good.sizeIds,
			colorIds : good.colorIds,
			goodsSn : good.goodsSn,
			blandId : good.blandId,
			name : good.name,
			barCode:good.barCode,
			discount:rowData.discount
		};
        
        
        $scope.initPacketNumber(good.goodsSn, good.packetNumber);
        
        var isShowSel = $scope.showAndProTwoDimensionSel($scope.currentRowData);
        if(isShowSel){
        	$("#list4").setRowData($scope.rowId, {name: $scope.currentRowData['name']});
        } else {
        	delRow(null, $scope.rowId);
        }
    };
    
    /**
     * 获取包装数值
     */
    $scope.initPacketNumber = function(goodsSn, packetNumber){
    	var flag = false;
        for(var i = 0; i < $scope.snPacketArr.length; i++){
        	for(var snPacket in $scope.snPacketArr[i]){
        		if(snPacket == $scope.currentRowData['goodsSn']){
        			if(!$scope.snPacketArr[i][snPacket]){
        				$scope.packetNumber = 1;
        			}else{
        				$scope.packetNumber =  $scope.snPacketArr[i][snPacket];
        			}
        			//复制为新增时没有$scope.packetNumbers
        			if(!$scope.packetNumbers || $scope.packetNumber != 1){
        				$scope.getPacketNumber($scope.packetNumber);
        			}
        			$scope.packetNumberDisabled = true;
        			flag = true;
        			break;
        		}
        	}
        }
        
        if(!flag){
            $scope.packetNumber =  packetNumber;
            $scope.packetNumberDisabled = false;
            $scope.getPacketNumber(packetNumber);//获取商品打包数
        }
    }
    
    /**
     * 在表格中自动完成输入框中点选尺码
     * @param good
     */
    $scope.selAutoSize = function(size,$event)
    {
        if($scope.curEditSizeInput != undefined)
        {
            $scope.curEditSizeInput.val(size.name);
        }
        $scope.selSize = size;
        $scope.showAutoSize = false;
    };

    /**
     * 在表格中自动完成输入框中点选颜色
     * @param good
     */
    $scope.selAutoColor = function(color,$event)
    {
       // stopEvent($event);
        if($scope.curEditColorInput != undefined)
        {
            $scope.curEditColorInput.val(color.name);
        }
        $scope.selColor = color;
        $scope.showAutoColor = false;
    };
    
    /**
     * 在表格中自动完成输入框中点选价格
     * @param good
     */
    $scope.selAutoPrice = function(price,$event)
    {
    	//stopEvent($event);
    	if($scope.curEditPriceInput != undefined)
    	{
    		$scope.curEditPriceInput.val(price.value);
    	}
    	$scope.showAutoPrice = false;
    };
    
    
    /**
     * 在表格中自动完成输入框中点选价格
     * @param good
     */
    $scope.selAutoTruePrice = function(truePrice,$event)
    {
    	//stopEvent($event);
    	if($scope.curEditTruePriceInput != undefined)
    	{
    		$scope.curEditTruePriceInput.val(truePrice.value);
    	}
    	$scope.showAutoTruePrice = false;
    };
    
    /** 获取商品属性里的包装数*/
    $scope.getPacketNumber = function(packetNumber){
    	if(!packetNumber || packetNumber == 1){
        	$scope.packetNumbers = [1];
        }else{
        	$scope.packetNumbers = [1, packetNumber]
        }
    }
    
    
    /**是否提示包装数不能修改 */
    $scope.packetNumberOver = function(){
    	if($scope.packetNumberDisabled && !$scope.showRemind){
    		$scope.showRemind = true;
    	}
    }
    
    /**
     * 保存草稿
     */
    $scope.saveOrder = function($event)
    {
    	$("#list4").jqGrid("saveCell",lastrow,lastcell);
    	stopEvent($event);
    	var rowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
        if (rowData.length < 1) { alert("请输入采购商品信息！"); return; }
        $scope.saveUrl = "purchaseSaveDraft.ac";
        $scope.loadingTips = "保存中...";
        $scope.saveOrderThread(rowData); 
    };
    
    /**
     * 复制为销售单
     */
    $scope.changeToWholesaleOrder = function($event) {
    	window.open(base+"/admin/inner/sale/wholesaleOrdersList.ac?mid=4&purchaseSn="+$scope.order.purchaseSn,"_blank");
    };

    /**
     * 复制为库存调拨单
     */
    $scope.changeToStoreTransferOrder = function($event) {
        window.open(base+"/admin/inner/storehouse/storeTransferOrder/storeTransferOrderList.ac?mid=4&purchaseSn="+$scope.order.purchaseSn,"_blank");
    };
    
	 /**
     * 删除订单
     */
    $scope.deleteOrder = function($event)
    {
    	if (confirm("确认要删除该单据吗？")) {
    		$scope.loadingTips = "删除中...";
	    	$scope.loadingOrder = true;
	    	httpServices.post("orderDelete.ac?purchaseSn="+$scope.order.purchaseSn).success(function(result) {
	    		$scope.loadingOrder = false;
	    		if(result.statusCode == 1)
	    		{
	    			$scope.addOrderForm(); //新增
	    			showMessage(result.title, result.content, 2000);
	    			$("#listGrid").trigger("reloadGrid");
	    		}else{
	    			alert(result.content);
	    		}
			});
    	}
    };
    
    /**
     * 已采购单据撤销
     */
    $scope.destroyOrder = function($event)
    {
    	if(!dateIsEquals(new Date($scope.order.businessTime),new Date()) && RESOURCES.indexOf(GL_CONS.CHANGE_BUSINESS_TIME) == -1 ){
    		alert(GL_CONS.CHANGE_BUSINESS_TIME_ERROR);
    		return;
    	}
    	var confirmTips = "单据撤销将撤销相应的库存、账务，且撤销后不可恢复，是否确认撤销该单据？";
    	
    	if (confirm(confirmTips)) {
    		$scope.loadingTips = "撤销处理中...";
        	$scope.loadingOrder = true;
	    	httpServices.post("purchaseOrderDestroy.ac?purchaseSn="+$scope.order.purchaseSn).success(function(result) {
	    			$scope.loadingOrder = false;
	            	if(result.statusCode == 1)
	            	{
	            		showMessage(result.title, result.content, 2000);
	            		$("#listGrid").trigger("reloadGrid");
	            		$scope.loadOneOrder(result.object.purchaseSn);
	            		$scope.getSupplierInfo();
	            	}else{
	            		alert(result.content);
	            		$scope.loadOneOrder($scope.order.purchaseSn);
	            		$("#listGrid").trigger("reloadGrid");
	            	}
			});
    	}
    };
    
    /**
     * 去入库
     * 
     */
    $scope.goForInStore = function($event) {
    	window.open(base+"/admin/inner/storehouse/win/storeInOrdersList.ac?mid=4&onLoadOrdersSn="+$scope.order.purchaseSn,"_blank");
    }
    
    /**
     * 一键入库
     * 
     */
    $scope.inStoreByOneTime = function($event) {
    	if(!dateIsEquals(new Date($scope.order.businessTime),new Date()) && RESOURCES.indexOf(GL_CONS.CHANGE_BUSINESS_TIME) == -1 ){
    		alert(GL_CONS.CHANGE_BUSINESS_TIME_ERROR);
    		return;
    	}
    	
		$scope.loadingTips = "入库处理中...";
    	$scope.loadingOrder = true;
    	httpServices.post("inStoreByOneTime.ac?purchaseSn="+$scope.order.purchaseSn).success(function(result) {
    			$scope.loadingOrder = false;
            	if(result.statusCode == 1)
            	{
            		showMessage(result.title, result.content, 2000);
            		$("#listGrid").trigger("reloadGrid");
            		$scope.loadOneOrder(result.object.orderSn);
            		$scope.getSupplierInfo();
            	}else{
            		alert(result.content);
            		$scope.loadOneOrder($scope.order.purchaseSn);
            		$("#listGrid").trigger("reloadGrid");
            	}
		}).error(function(result){
			$scope.loadingOrder = false;
		});
    }
    
    /**
     * 提交单据
     */
    $scope.approvalConfirm = function($event)
    {
    	if(!dateIsEquals(new Date($scope.order.businessTime),new Date()) && RESOURCES.indexOf(GL_CONS.CHANGE_BUSINESS_TIME) == -1 ){
    		alert(GL_CONS.CHANGE_BUSINESS_TIME_ERROR);
    		return;
    	}
    	$("#list4").jqGrid("saveCell",lastrow,lastcell);
    	stopEvent($event);
    	var rowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
        if (rowData.length < 1) { alert("请输入采购商品信息！"); return; }
        $scope.saveUrl="approvalConfirmPurchase.ac";
        $scope.loadingTips = "采购处理中...";
        $scope.saveOrderThread(rowData); 
    	
    };
    
    /**
     * 打印
     */
    $scope.toPrint = function() {
    	if($scope.notSaveOrder){
    		alert("亲，请保存单据后再打印哦！");
    		return;
    	}
    	toPrint($scope,httpServices,'/admin/system/printTemplate/printTemplateListJSON.ac?orderType=21');
    };
    
    $scope.refreshPrintTemplate = function(){
    	refreshPrintTemplate($scope,httpServices,'/admin/system/printTemplate/printTemplateListJSON.ac?orderType=21');
    };

	$scope.selTemplate = function(templateId) {
		selTemplate($scope,httpServices,ipCookie,templateId,$scope.order.purchaseSn,21,"/admin/inner/orders/purchase/purchasePrint.ac");
	};
    
    /**
     * 对比原订单
     */
    $scope.toCompare = function($event)
    {
    	if(!$scope.order.ordersSn){
			$scope.warningMsg = "该采购单没有对应的采购订单.";
    		showAlert();
    		return;
		}
    	self.location.href = "toComparePage.ac?mid=2&purchaseSn="+$scope.order.purchaseSn;
    	
    };
    
    
    
    /**
     * 订单提供线程
     */
    $scope.saveOrderThread = function(rowData)
    {
    	$scope.orderGoods = []; //完整的商品数据
    	if(($scope.order.trueTotalAmount && $scope.order.trueTotalAmount > 100000000)
    			|| ($scope.order.totalAmount && $scope.order.totalAmount > 100000000)){
    		$scope.warningMsg = "金额、实付金额不能超过1亿.";
    		showAlert();
    		return;
    	}

    	//检验商品
        for (var i = 0; i < rowData.length; i++) {
            if(rowData[i].goodsSn != undefined && rowData[i].goodsSn !="" )
            {
            	if(rowData[i].colorId == undefined || rowData[i].colorId =="")
            	{
            		setTimeout(function() { $('#list4').editCell(i+1, 12, true); }, 50);  
            		//$('#list4').editCell(i, 8, true);      //设置聚焦
            		$scope.warningMsg = "请选择颜色.";
            		showAlert();
            		return;
            	}
            	if(rowData[i].sizeId == undefined || rowData[i].sizeId =="")
            	{
            		setTimeout(function() { $('#list4').editCell(i+1, 13, true); }, 50);  
            		//$('#list4').editCell(i, 8, true);      //设置聚焦
            		$scope.warningMsg = "请选择尺码.";
            		showAlert();
            		return;
            	}
            	if(rowData[i].quantity == undefined || rowData[i].quantity =="")
            	{
            		setTimeout(function() { $('#list4').editCell(i+1, 15, true); }, 50);  
            		//$('#list4').editCell(i, 8, true);      //设置聚焦
            		$scope.warningMsg = "请输入数量.";
            		showAlert();
            		return;
            	}
            	
            	if($scope.order.supplierId == undefined || $scope.order.supplierId == ''){
            		$scope.warningMsg = "请选择供应商.";
            		showAlert();
            		return;
            	}else if($scope.order.depotId == undefined || $scope.order.depotId == ''){
            		$scope.warningMsg = "请选择进货仓库.";
            		showAlert();
            		return;
            	}
            	
            	$scope.orderGoods.push({goodsSn:rowData[i].goodsSn, color:rowData[i].colorId, size:rowData[i].sizeId, quantity:rowData[i].quantity,price:rowData[i].price,truePrice:rowData[i].truePrice,amount:rowData[i].amount,trueAmount:rowData[i].trueAmount,discount:rowData[i].discount,packetNumber: rowData[i].packetNumber,showOrder:i});
            }else if(i==0){
            	
            	setTimeout(function() { $('#list4').editCell(i+1, 8, true); }, 50);  
            	$scope.warningMsg = "请选择商品.";
        		showAlert();
        		return;
            }
        }
        
        if($scope.order.businessTime){   //业务时间的时点设置为当前，日期不动
        	var now = new Date();
        	var businessDay = new Date($scope.order.businessTime);
        	businessDay.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
        	$scope.order.businessTime = businessDay.getTime();
        }
        
    	$scope.loadingOrder = true;
        //提交订单
		httpServices.post($scope.saveUrl,$.param({order:angular.toJson($scope.order),goods:angular.toJson($scope.orderGoods)}),{
            headers:
            {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function(result) {
        	$scope.loadingOrder = false;
        	var orderid = $scope.order.id;
        	if(result.statusCode == 1)
        	{
        		// 如果单据id不存在的情况在上传
        		if(!orderid) {
        			$scope.uploadImages(result.object.id);
        		}
        		showMessage(result.title, result.content, 2000);
        		$("#listGrid").trigger("reloadGrid");
        		$scope.loadOneOrder(result.object.purchaseSn);
        		$scope.getSupplierInfo();
        	}else{
    			alert(result.content);
    		}
		}).error(function(){
    			$scope.loadingOrder = false;
    	});
    }; //订单提供线程end
    
    /**
     * 加载一个订单
     */
    $scope.loadOneOrder = function(purchaseSn)
    {
    	$scope.notSaveOrder = false;
    	$scope.showScanCode = false;//隐藏扫描输入框
    	$scope.loadingTips = "加载中...";
    	$scope.loadingOrder = true;
    	var paramsJson = {purchaseSn:purchaseSn};
    	$scope.editForm.$setPristine();//清除当前状态
    	$scope.getSupplierInfo();
    	$scope.imgList = [];
    	$scope.snPacketArr = [];
    	
    	httpServices.post(base + '/admin/inner/orders/purchase/purchaseGet.ac',{},{params:paramsJson}).success(function(data) {
    		if(data.statusCode != 1) {
    			alert(data.content);
    			$scope.loadingOrder = false;
    			return ;
    		}
        	$scope.order = angular.copy(data.order);  //直接赋值到表单
        	if(!$scope.order.businessTime){
        		$scope.order.businessTime = $scope.order.updateTime;
        	}
        	
        	if(!$scope.order.wipeZero){
        		$scope.order.wipeZero = 0;
        	}
        	if(!$scope.order.otherCost){
        		$scope.order.otherCost = 0;
        	}
        	
        	// 判断是否由于门店限制而不能修改单据
        	$scope.isReadonly = isReadonlyBySpendableAccount(userLoginInfoJSON,$scope.isReadonly,$scope.order.accountId);
        	$scope.isReadonly = isReadonlyBySpendableStorehouse(userLoginInfoJSON,$scope.isReadonly,$scope.order.depotId);
        	
        	$scope.order.supplier = {id:data.order.supplierId,val:data.order.supplierId,text:data.order.supplierName,discount:data.order.supplierDiscount};
        	$scope.order.depot = {val:data.order.depotId,text:data.order.depotName};
        	$scope.selAccount = {val:data.order.accountId,text:data.order.accountName};
        	//更新商品表格
        	jQuery("#list4").jqGrid("clearGridData");
        	
        	if(maxRowId == undefined)
    	    {
    	        maxRowId = jQuery("#list4").jqGrid('getDataIDs').length;
    	    }
        	
        	if(data.orderGoods.length ==0)  //如果还没有商品，则添加5个空行
        	{
        		for ( var i = 0; i <= 5; i++) {
    	            addNewEmptyRow();

    	        }
        	}
        	else
        	{
        		var snPacket = {};
        		for(var i=0; i<data.orderGoods.length; i++)
            	{
        			var flag = false;
            		maxRowId = maxRowId+1;
            		data.orderGoods[i]['name'] = data.orderGoods[i]['goodName'];
            		for(var sp in snPacket){
            	    	if(sp == data.orderGoods[i]['goodsSn']){
            	    		flag = true;
            	    		break;
            	    	}
            	    }
            	    if(!flag){
            	    	snPacket[data.orderGoods[i]['goodsSn']] = data.orderGoods[i]['packetNumber'];
            	    }
            	    $('#list4').jqGrid('addRowData', maxRowId,data.orderGoods[i]);
            	}	
        		$scope.snPacketArr.push(snPacket);
        	}
        	$scope.loadingOrder = false;
        	$scope.setOperation();
        	$scope.order.alreadyPaid = data.order.alreadyPaid;
        	
        	// 自动更新供应商上次价格
        	if($scope.order.state == 1) {
        		var allRowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
        		var goodsSnArr = [];
        		for(var i = 0;i < allRowData.length;i++){
        			if(allRowData[i]['goodsSn']){
        				goodsSnArr.push(allRowData[i]['goodsSn']);
        			}
        		}
        		if($scope.order.supplierId) {
        			$scope.updateSupplierPrice($scope.order.supplierId, goodsSnArr, $scope.updateSupplierPriceByGoodsList, {});
        		}
        	}
        	
        	//查询图片
        	if($scope.order.id){
        		httpServices.get(base + '/admin/inner/orders/purchase/images/purchaseOrdersImgs.ac?orderId='+$scope.order.id).success(function(data){
            		$scope.imgList = data.rows;
        			if($scope.imgList){
        				for(var i =0 ; i < $scope.imgList.length ; i++){
        					$scope.imgList[i].showIndex = $scope.showIndex;
        				}
        			}
            	}).error(function(data, status) {});
        	}
            $scope.initChangeOrderRows();
        });
    };
    
    /**
     * 设置空的新增form
     */
    $scope.addOrderForm = function()
    {
    	$scope.isReadonly = isReadonly;
    	$scope.initOrder();
    	$scope.notSaveOrder = false;
    	$scope.showScanCode = false;//隐藏扫描输入框
    	$scope.order.finalTotalAmount = 0;
    	$scope.imgList = [];
    	$scope.setOperation();
    	$scope.snPacketArr = [];
    	$scope.packetNumberDisabled = false;
        $scope.changeOrderRows = [];
    	//更新商品表格
    	jQuery("#list4").jqGrid("clearGridData");
    	
    	for ( var i = 0; i <= 5; i++) {
            addNewEmptyRow();

        }
    };
    
    /*复制为新增*/
    $scope.copyOrderForm = function(){
    	//三个月之前的单据
    	if (addDate(new Date($scope.order.businessTime), 89) < new Date()) {
    		if(confirm("该单据业务日期为90天之前，确定后将默认修改为今天。")){
    			$scope.order.businessTime = new Date();
    		}else{
    			return;
    		}
		}
    	$scope.isReadonly = isReadonly;
    	$scope.notSaveOrder = false;
    	$scope.showScanCode = false;//隐藏扫描输入框
    	$scope.order.purchaseSn = '';
    	$scope.order.ordersSn = '';
    	$scope.order.state = 1;
    	$scope.order.id = null;
        $scope.changeOrderRows = [];
    	var temAlreadyPaid = $scope.order.alreadyPaid;
    	$scope.setOperation();
    	$scope.order.alreadyPaid = temAlreadyPaid;
    	
    	$scope.updatePriceList();
    	
    };
    
    $scope.showScanInput = function(){
    	$scope.showScanCode = !$scope.showScanCode;
    	setTimeout(function(){
    		$("#barCode").focus();
    	},200);
    	
    };
    
    $scope.getEmptyRowId = function(){
    	var rowIds = $("#list4").jqGrid("getDataIDs");
    	for (var j = 0; j < rowIds.length; j++) {
    		var thisRow = $("#list4").jqGrid("getRowData",rowIds[j]); //当前行数据
    		if(thisRow['name'] == ""){
    			return rowIds[j];
    		}
    	}
    	return -1;
    };
    
     $scope.searchGoodsByBarcode = function(e){
    	if(e.keyCode=='13'){
    		stopEvent(e);
    		var barCode = $scope.barCode;
    		$scope.barCode = "";
			$("#barCode").focus();
    		if(!barCode || barCode === 0){
    			$scope.warningMsg = "请输入条码";
	    		showAlert();
    			return;
    		}
    		var paramsJson = {searchKey:barCode};

    		httpServices.post(base+"/admin/inner/goods/goodsSelectForOrder.ac",{},{params:paramsJson}).success(function(data) {
    			var goods = data.optionList;
    			if(goods.length == 0){
    				$scope.warningMsg = barCode+" 查无此商品！";
    	    		showAlert();
    	    		_playSound.play();
    			}else if(goods.length == 1){
    				var rowId = $scope.getEmptyRowId();
    				if(rowId == -1){
    					addNewEmptyRow();
    					rowId = maxRowId;
    				}else if(rowId == maxRowId){
    					addNewEmptyRow();
    				}
    				$scope.rowId = rowId;

    				var rowData = $("#list4").jqGrid("getRowData", rowId);
    				var good = goods[0];
    				$scope.selGood = good;
    				$scope.showAutoGoods = false;
    				//准备弹出二维录入框
    				var currentRowData = {
    						unit : good.unit,
    						quantity : 1,
    						price : good.factoryPrice,
    						amount : good.factoryPrice,
    						sizeIds : good.sizeIds,
    						colorIds : good.colorIds,
    						goodsSn : good.goodsSn,
    						blandId : good.blandId,
    						name : good.name,
    						barCode:good.barCode,
    						discount:rowData.discount
    				};
    				$scope.currentRowData = angular.copy(currentRowData);
    				
    				$scope.initPacketNumber(good.goodsSn, good.packetNumber);
    				
    				var currentSizes = [];   //当前商品所拥有的尺码
    				var currentColors = []; //当前商品所拥有的颜色

    				var curGoodSn = currentRowData['goodsSn']; //行货号
    				if(curGoodSn == undefined || curGoodSn == "")
    				{
    					return;
    				}

    				$scope.getStoredCount(curGoodSn); //获取商品库存信息
    				//为了不保留原来的输入数据，这里重新申请了空间。
    				currentSizes =  $filter('filter')(angular.copy(idStringToObjectArray($scope.allSizes, currentRowData['sizeIds'], 'id', ',')),{status:1});
    				if(currentSizes.length == 0){
    					$scope.warningMsg = '商品 【' + currentRowData.goodsSn + ' ' + currentRowData.name + '】没有可用的尺码！';
    		    		showAlert();
    					return;
    				}
    				currentColors = $filter('filter')(angular.copy(idStringToObjectArray($scope.allColors, currentRowData['colorIds'], 'id', ',')),{status:1});
    				if(currentColors.length == 0){
    					$scope.warningMsg = '商品 【' + currentRowData.goodsSn + ' ' + currentRowData.name + '】没有可用的颜色！';
    		    		showAlert();
    					return;
    				}
    				$scope.currentSizes = angular.copy(currentSizes);
    				$scope.currentColors = angular.copy(currentColors);
    				var skuColor = getObject($scope.allColors, 'id', good.skuColorId);
    				var skuSize = getObject($scope.allSizes, 'id', good.skuSizeId);
    				$( "#twoDisDiv" ).dialog({ title: currentRowData.name+" "+currentRowData.goodsSn,dialogClass: 'twoDisDiv'});
    				if(good.isUnique && good.skuBarCode && (skuColor.status == 0 || skuSize.status == 0)){
						$scope.warningMsg = '单品 【' + good.skuBarCode + ' ' + good.name + '】的颜色或尺码已停用！';
    		    		showAlert();
    					return;
					}
    				$("#list4").setRowData(rowId, {name: currentRowData['name']});
    				if((currentSizes.length == 1 && currentColors.length == 1) 
    						|| (good.isUnique && good.skuBarCode && skuColor.status == 1 && skuSize.status == 1)){
    					var colorId = parseInt(good.skuColorId?good.skuColorId:good.colorIds);
    					var sizeId = parseInt(good.skuSizeId?good.skuSizeId:good.sizeIds);
    					var colorIndex = keyIndexOfArr(colorId,currentColors,"id");
    					var sizeIndex = keyIndexOfArr(sizeId,currentSizes,"id");
    					$scope.selIndexX = sizeIndex; //二维录入中，横向选中下标
    					$scope.selIndexY = colorIndex; //二维录入中，竖向选中下标
    					if($scope.manualAddNumber){
    						$scope.updateSupplierPrice($scope.order.supplierId, [curGoodSn], function(result) {
    							$scope.getOneGoodSupplierPrices(result, {goodsSn:curGoodSn});
    							$( "#twoDisDiv" ).dialog("option",{close:function(){
    								$("#list4").setRowData(rowId,{name:""});
    							},focus:function(){
    								$scope.barCodeFocus = true;//设置焦点在扫描输入框
    								$("#goods"+colorIndex+"_"+sizeIndex).focus();
    							}});
    							$( "#twoDisDiv" ).dialog( "open" );
    						});
    					}else{
    						$scope.notSaveOrder = true;
    						currentColors[colorIndex][sizeId] = 1;
    						httpServices.post(base + '/admin/inner/supplier/getSupplierWithPrices.ac',$.param({id:$scope.order.supplierId,goodsSnArr:[curGoodSn]}),{
    				            headers:
    				            {
    				                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    				            }
    				        }).success(function(result) {
    				        	if(result.statusCode == 1) {
    				        		$scope.supplierDiscount = (result.object.objSupplier && result.object.objSupplier.discount)?result.object.objSupplier.discount:100;
    				        		if(angular.isArray($scope.lastSupplierPrices)){

        								//从价格信息组中剔除当前商品的旧价格信息
        								for (var priceTemp in $scope.lastSupplierPrices){
        									if(priceTemp['goodsSn'] == curGoodSn){
        										remove($scope.lastSupplierPrices, priceTemp);
        									}
        								}

        								$scope.lastSupplierPrices = $scope.lastSupplierPrices.concat(result.object.goodsPricesList);
        							}else{
        								$scope.lastSupplierPrices = result.object.goodsPricesList;
        							}
    				        		
    				        		//获取输入的数据
    	    				    	var insertModels = [];
    	    						if( $scope.storedCount == undefined){
    	    							$scope.storedCount = [];
    	    						}
    	    				    	for(var i=0; i<currentColors.length; i++)
    	    				    	{
    	    				    		var color = currentColors[i];
    	    				    		for(var j=0; j<currentSizes.length; j++)
    	    				    		{
    	    				    			
    	    				    			var size = currentSizes[j];
    	    				    			if(color[size.id] != undefined)
    	    				    			{
    	    				        			if( $scope.storedCount[currentColors[i].id] == undefined){
    	    				        				$scope.storedCount[currentColors[i].id] = [];
    	    				        			}
    	    				        			currentRowData.sizeId = size.id;
    	    				        			currentRowData.colorId = color.id;
    	    				        			currentRowData.quantity = accMul(color[size.id], $scope.packetNumber);
    	    				        			var property = $scope.getGoodPropertyAfterCalc(currentRowData);
    	    				        			
    	    									 var newModel = {
    	    										goodsSn : currentRowData.goodsSn,
    	    										goodName : currentRowData.name,
    	    										barCode : currentRowData.barCode,
    	    										name:currentRowData.name,
    	    										discount : property.discountTemp,
    	    										sizeId : size.id,
    	    										sizeName : size.name,
    	    										colorId : color.id,
    	    										colorName : color.name,
    	    										quantity : accMul(color[size.id], $scope.packetNumber),
    	    										price : property.priceTemp,
    	    										truePrice: property.truePriceTemp,
    	    										unit : currentRowData.unit,
    	    										colorIds : currentRowData.colorIds,
    	    										sizeIds : currentRowData.sizeIds,
    	    										amount: property.amountTemp,
    	    										trueAmount: property.trueAmountTemp,
    	    										factoryPrice: property.factoryPriceTemp,
    	    										supplierPrice: property.supplierPriceTemp,
    	    										supplierTruePrice: property.supplierTruePriceTemp,
    	    										number:$scope.storedCount[currentColors[i].id][currentSizes[j].id],
    	    										packetNumber: $scope.packetNumber,
    												packetCount: 1
    	    									};
    	    									 
    	    				    				insertModels.push(newModel);
    	    				    				if(aboveMaxQuantity(insertModels)){
    	    				    				    $("#list4").jqGrid("delRowData", rowId);
    	    				    				    return;
    	    				    				}
    	    				    			}
    	    				    		}
    	    				    	}
    	    				    	
    	    				    	
    	    				    	//把输入的数据插入订单-商品明细表中
    	    				    	if(maxRowId == undefined)
    	    					    {
    	    					        maxRowId = jQuery("#list4").jqGrid('getDataIDs').length;
    	    					    }
    	    				    	
    	    				    	/*判断新增加的单品是否已在列表中存在，如果存在则把新增加单品的数量添加到已存在的记录中*/
    	    				    	var sameNumber = 0; //二维录入框中的商品存在于原商品明细表标志（如果存在则合并数量）
    	    				    	var notDeleteFlag = false;//二维录入框中的商品与当前编辑行商品一致，则不删除当前行
    	    				    	var rowIds = jQuery("#list4").jqGrid('getDataIDs'); 
    	    				    	var snPacket = {};
    	    						for(var i=0; i<insertModels.length; i++)
    	    				    	{
    	    							
    	    							var existsSameFlag = false;
    	    					        for (var j = 0; j < rowIds.length; j++) {
    	    					        	var thisRow = $("#list4").jqGrid("getRowData",rowIds[j]); 
    	    					        	if(thisRow['goodsSn'] == insertModels[i]['goodsSn'] && thisRow['colorId'] == insertModels[i]['colorId'] && thisRow['sizeId'] == insertModels[i]['sizeId']){
    	    					        		
    	    					        		if(rowIds[j] == rowId ){//如果是与当前行商品一致，则不合并数量，而是把数量覆盖
    	    					        			$("#list4").setRowData(rowIds[j], {
    	    					        				packetCount :parseInt(insertModels[i]['packetCount']),
    							        				packetNumber :parseInt(insertModels[i]['packetNumber']),
    	    											quantity :parseInt(insertModels[i]['quantity']),
    	    											amount :  accMul(parseInt(insertModels[i]['quantity']) , thisRow['price']),
    	    											trueAmount: accMul(parseInt(insertModels[i]['quantity']),thisRow['truePrice'])
    	    										});
    	    					        			notDeleteFlag = true;
    	    					        		}else{
    	    					        			if(thisRow['packetNumber'] != insertModels[i]['packetNumber']){
    							        				$("#list4").setRowData(rowIds[j], {
    							        					packetCount :parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
    							        					packetNumber :insertModels[i]['packetNumber'],
    							        					quantity : accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity']),
    							        					amount : accMul((accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])),thisRow['price']),
    							        					trueAmount: accMul((accMul(parseInt(thisRow['packetCount']),insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])),thisRow['truePrice']) 
    							        				});
    							        			}else{
    							        				$("#list4").setRowData(rowIds[j], {
    							        					packetCount :parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
    							        					packetNumber :parseInt(insertModels[i]['packetNumber']),
    							        					quantity : parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity']),
    							        					amount : accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])),thisRow['price']),
    							        					trueAmount: accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])),thisRow['truePrice']) 
    							        				});
    							        			}
    	    					        		}
    	    					        		$scope.warningMsg = good.name+'，'+good.goodsSn+'，'+currentColors[colorIndex]['name']+'，'+currentSizes[sizeIndex]['name']+'，累计数量：'+$('#list4').getRowData(rowIds[j])['quantity'];
    	    						    		showAlert();
    	    					        		existsSameFlag = true;
    	    					        		++sameNumber;
    	    					        		break;
    	    					        	}
    	    					        }
    	    					        
    	    					        var spFlag = false;
    	    					        for(var k = 0; k < $scope.snPacketArr.length; k++){
    	    				                for(var sp in $scope.snPacketArr[k]){
    	    				                    if(sp == insertModels[i]['goodsSn']){
    	    				                    	spFlag = true;
    	    				                    	break;
    	    				                    }
    	    				                }
    	    				            }
    	    					        if(!spFlag){
    	    					        	//由于开过单的商品下次就只有一个选项，所以此处不需要再判定是否已经有开过此商品
    	    					        	snPacket[insertModels[i]['goodsSn']] = insertModels[i]['packetNumber'];
    	    					        	$scope.snPacketArr.push(snPacket);
    	    					        }
    	    							
    	    							if(!existsSameFlag){
    	    					    		maxRowId = maxRowId+1;
    	    					    		if(i-sameNumber == 0){
    	    					    			$('#list4').jqGrid('addRowData', maxRowId,insertModels[i],"after",parseInt(rowId));
    	    					    		}else{
    	    					    			$('#list4').jqGrid('addRowData', maxRowId,insertModels[i],"after",maxRowId-1);
    	    					    		}
    	    					    		$scope.warningMsg = good.name+'，'+good.goodsSn+'，'+currentColors[colorIndex]['name']+'，'+currentSizes[sizeIndex]['name']+'，累计数量：'+$('#list4').getRowData(maxRowId)['quantity'];
    							    		showAlert();
    	    							 }
    	    				    	}	
    	    								
    	    						if(!notDeleteFlag && jQuery("#list4").jqGrid('getDataIDs').length > 1){
    	    							$("#list4").jqGrid("delRowData", rowId);
    	    						}

    	    						if(jQuery("#list4").jqGrid('getDataIDs').length < 6){
    	    							addNewEmptyRow();
    	    						}
    	    						
    	    						if(insertModels.length > 0){
    	    							 //更新合计行上的合计指标
    	    		        	        updateTotalNumbers();
    	    					        setTimeout(function(){	
    	    									 $scope.$apply(function(scope){
    	    										 if(scope.businessConfig.zeroPaid == 1){
    	    											 scope.order.alreadyPaid = 0;
    	    										 }else{
    	    											 scope.order.alreadyPaid = scope.order.finalTotalAmount;
    	    										 }
    	    							    	});
    	    								 });
    	    						}
    	    						
    	    						var emptyRowId = $scope.getEmptyRowId();
    	    						if(emptyRowId == -1){
    	    							addNewEmptyRow();
    	    							emptyRowId = maxRowId;
    	    						}
    				        	}
    				        });
    					}
    				}else{
    					$scope.updateSupplierPrice($scope.order.supplierId, [curGoodSn], function(result) {
    						$scope.getOneGoodSupplierPrices(result, {goodsSn:curGoodSn});
    						$scope.selIndexX = 0; //二维录入中，横向选中下标
    						$scope.selIndexY = 0; //二维录入中，竖向选中下标
    						$( "#twoDisDiv" ).dialog("option",{close:function(){
    							$("#list4").setRowData(rowId,{name:""});
    						},focus:function(){
    							$scope.barCodeFocus = true;//设置焦点在扫描输入框
    						}});
    						$( "#twoDisDiv" ).dialog( "open" );
    					});
    				}
    			}else{
    				$scope.barCode = "";
    				$("#barCode").focus();
    				$scope.warningMsg = barCode+" 存在多个商品，不能直接通过扫码添加到列表中！";
    	    		showAlert();
    			}

    		});
    	}
    };
    
    $scope.toPrintBarcodeList = function(){
    	window.open(base+"/admin/inner/goods/printBarcodeList.ac"+($scope.order.purchaseSn?("?ordersSn="+$scope.order.purchaseSn):""),"_blank");
    };
    
    //文件上传
    $scope.onFileSelect = function($files) {
    	if ($scope.imagesLoading || $scope.imgList.length > 4) {
			return;
		}

		$scope.imagesLoading = true;

		var fileLength = $files.length;
		if (fileLength <= 0) {
			$scope.imagesLoading = false;
		}
		
		for (var i = 0; i < fileLength; i ++) {
			var file = $files[i];
			if (file.size > 4194304) {
				$scope.imagesLoading = false;
				alert("文件不能大于4M.");
				break;
			}
			
			//获取oss直传授权地址
			httpServices.post(base + '/admin/file/img/getOrderUploadUrl.ac?module=purchaseOrderImages&fileName='+encodeURIComponent(file.name)).success(function(result) {
				if (result.statusCode == 1) {
					var formData = {
						'policy' : result.object.policy,
						'OSSAccessKeyId' : result.object.accessid,
						'success_action_status' : '200',
						'callback' : result.object.callback,
						'signature' : result.object.signature,
						'key' : result.object.storeName
					};
					
					if ($scope.order.id) {
						formData['x:orderid'] = $scope.order.id;
					}
					
					$scope.upload = $upload.upload({
						url : result.object.host,
						data : formData,
						file : file
					}).success(function(data, status, headers, config) {

						if (data.statusCode == 1) {
							//显示顺序加1 放到列表最后
							$scope.showIndex = $scope.showIndex + 1;
							$scope.imgList.push({
								name : data.object.name,
								url : data.object.url,
								imgId : data.object.id,
								id : data.object.orderImagesId,
								showIndex : $scope.showIndex
							});
						} else {
							alert(data.content);
						}
						$scope.imagesLoading = false;
					});
				}
				
			});
		}
    };
    
    //上传图片
    $scope.uploadImages = function(orderid) {
    	var imgIds = objectArrayToIdString($scope.imgList, "imgId", ",");
    	if(orderid) {
    		httpServices.post(base + '/admin/inner/orders/purchase/images/uploadOrdersImage.ac?orderId=' + orderid, $.param({imgIds : imgIds}),{
	             headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
    		}).success(function(result) {
				// 上传图片成功
				if(result.statusCode != 1) {
					alert("上传图片失败！");
				}
				
			}).error(function(data, status) {
				alert("上传图片失败！");
			});
    	}
    };
    
    //从相册中移除图片
    $scope.delRelImg = function(albumImg, $event) {
		stopEvent($event);
		var tip = confirm("确认要删除图片吗？");
		if(tip == true){
			if ($scope.order.id) {
				httpServices.post(base + '/admin/inner/orders/purchase/images/deleteOrdersImage.ac?albumId=' + albumImg.id).success(function(result) {
					removeByKey($scope.imgList, "imgId", albumImg.imgId);
				}).error(function(data, status) {
					$scope.histImgloading = false;
				});
			} else {
				removeByKey($scope.imgList, "imgId", albumImg.imgId);
			}
		}
	};
	
	//得到图片小图路径
	$scope.getSmallPictureUrl = function(url){
		if(url != undefined && url != ''){
			if(url.indexOf("qinsilk.com") != -1){
				return url;
			}else{
				return url;
			}
		}else{
			return url;
		}
	};
	
	/*********************图片滑动相册****************************************/
	$scope.direction = 'left';
    $scope.currentIndex = 0;

    $scope.setCurrentSlideIndex = function (index) {
        $scope.direction = (index > $scope.currentIndex) ? 'left' : 'right';
        $scope.currentIndex = index;
    };

    $scope.isCurrentSlideIndex = function (index) {
        return $scope.currentIndex === index;
    };

    $scope.prevSlide = function () {
        $scope.direction = 'left';
        $scope.currentIndex = ($scope.currentIndex < $scope.slides.length - 1) ? ++$scope.currentIndex : 0;
    };

    $scope.nextSlide = function () {
        $scope.direction = 'right';
        $scope.currentIndex = ($scope.currentIndex > 0) ? --$scope.currentIndex : $scope.slides.length - 1;
    };
    
    //打开相册前初始化
	$scope.initGallery = function(){
		$scope.slides = [];
		for(var i=0; i<$scope.imgList.length; i++) {
			$scope.slides.push({image:$scope.imgList[i].url});
		}
		
		$("#slideGallery").dialog("open");
		
	};  
    /*********************图片滑动相册 end****************************************/
	
	
	
	/********************* 供应商上次价格 start****************************************/
	
	$scope.updateSupplierPrice = function(supplierId, goodsSnArr, callback, otherParamter) {
		httpServices.post(base + '/admin/inner/supplier/getSupplierWithPrices.ac',$.param({id:supplierId,goodsSnArr:goodsSnArr}),{
            headers:
            {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function(result) {
        	if(result.statusCode == 1) {
        		$scope.supplierDiscount = (result.object.objSupplier && result.object.objSupplier.discount)?result.object.objSupplier.discount:100;
        		if(callback) {
            		callback(result.object, otherParamter);
            	}
        	}
        	
        });
	};
	
	$scope.updateSupplierPriceByGoodsList = function(result){
		var rowIds = jQuery("#list4").jqGrid('getDataIDs'); //获取所有行Id
		$scope.lastSupplierPrices = result.goodsPricesList;
        for (var i = 0; i < rowIds.length; i++) {
        	var thisRow = $("#list4").jqGrid("getRowData",rowIds[i]); //当前行数据
        	var property = $scope.getGoodPropertyAfterCalc(thisRow);
        	$("#list4").setRowData(rowIds[i], {
        		supplierPrice:property.supplierPriceTemp,
        		supplierTruePrice:property.supplierTruePriceTemp,
        		factoryPrice:property.factoryPriceTemp
        	});
        }
	};
	
	$scope.getOneGoodSupplierPrices = function(result, otherParamter) {
		if(angular.isArray($scope.lastSupplierPrices)){
    		
    		//从价格信息组中剔除当前商品的旧价格信息
    		for (var priceTemp in $scope.lastSupplierPrices){
        		if(priceTemp['goodsSn'] == otherParamter.goodsSn){
        			//remove($scope.lastSupplierPrices, priceTemp);
        			$scope.lastSupplierPrices.remove(priceTemp);
        		}
        	}
    		$scope.lastSupplierPrices = $scope.lastSupplierPrices.concat(result.goodsPricesList);
    	}else{
    		$scope.lastSupplierPrices = result.goodsPricesList;
    	}
	};
	
	/**
	 *  更新单价列表
	 */
	$scope.updatePriceList = function(){
    	if(RESOURCES.indexOf("purchaseOrderEdit") == -1){
    		return;
    	}
		var allRowData = $("#list4").jqGrid("getRowData"); //所有的行的数据
		var goodsSnArr = [];
		for(var i = 0;i < allRowData.length;i++){
			if(allRowData[i]['goodsSn']){
				goodsSnArr.push(allRowData[i]['goodsSn']);
			}
		}
		if($scope.order.supplierId){
			$scope.updateSupplierPrice($scope.order.supplierId,goodsSnArr,$scope.updatePriceListCallback,{})
		}
	};
	
	$scope.updatePriceListCallback = function(result) {
		$scope.supplierDiscount = (result.objSupplier && result.objSupplier.discount)?result.objSupplier.discount:100;
		$scope.updateSupplierPriceByGoodsList(result); 
	}
	
	/**
     * 跳转到客户对账单页面
     * */
    $scope.searchClientRecord =function() {
    	var clientName = ($scope.order.supplier)? $scope.order.supplier.text : '';
    	var clientId = ($scope.order.supplier)? $scope.order.supplier.val : '';
    	if(!clientName || !clientId) {
    		$scope.warningMsg = "请选择供应商!";
    		showAlert();
    		return;
    	}
    	var href= '/is/admin/inner/finance/banlance/record/supplierRecordList.ac?mid=67&searchSupplierRecord=searchSupplierRecord(' + clientId + ','+escape('"'+clientName+'"')+')';
    	window.open(href);
    }
	
	/********************* 供应商上次价格 end****************************************/
    
    $scope.helpUrl = GL_CONS.HELP_URL.purchaseListHelp;

    /**
     * 初始化转单下拉框行数
     */
    $scope.initChangeOrderRows = function () {
        $scope.changeOrderRows = new Array();
        if (($scope.order.state == 2)
            && $scope.order.purchaseSn  && ($scope.resources.indexOf('approvalConfirmWholesaleOrders') != -1)) {
            $scope.changeOrderRows.push("<a href=\"#\" class=\"ng-scope\" ng-click='changeToWholesaleOrder($event)' style=\"color: white;text-decoration: none;\">复制为销售单</a>");
        }

        if (($scope.order.state == 1 || $scope.order.state == 2 || $scope.order.state == 9)
            && $scope.order.purchaseSn && ($scope.resources.indexOf('storeTransferOrderConfirm') != -1 || $scope.resources.indexOf('storeTransferOrderSaveDraft') != -1)) {
            $scope.changeOrderRows.push("<a href=\"#\" class=\"ng-scope\" ng-click='changeToStoreTransferOrder($event)' style=\"color: white;text-decoration: none;\">复制为库存调拨单</a>");
        }
        $scope.$apply();
    };
});





/**
 * 显示弹框
 */
var timeout;
function showAlert()
{
	if(timeout != undefined)
	{
		clearTimeout(timeout) ;
	}
	$('.alert').css("zIndex",1005).show();
	timeout = setTimeout(function() { $(".alert").hide(); }, 3000);  
}
function aboveMaxQuantity(insertModels){
	var rowLength = $("#list4").jqGrid("getDataIDs").length;
	var availableRows = getScope("OrderCtrl").order.totalAvailableRows;
	if(availableRows != null && availableRows != undefined){
		if(insertModels && (availableRows + insertModels.length ) > 501){
			getScope("OrderCtrl").warningMsg = "列表中的商品过多，最多只能有500条记录";
			showAlert();
			return true;
		}
	}
	return false;
}
$(document).ready(
	    function() {
	        /**
	         * 自定义商品编辑生成函数
	         * @param value
	         * @param options
	         * @returns {string}
	         */
	        function goodElement(value, options) {
	            var t = '<input type="text"  maxlength="128" placeholder="货号、名称、条码" oninput="changAutoGoods(this)" onpropertychange ="changAutoGoodsIE(event)" onfocus ="loadGoodsFirst(this)" onkeydown="goodsSearchPress(event,this)" autocomplete="off" class="textbox goodsAuto" value="'+value+'" ><span  class="ui-icon-ellipsis" onclick="showTwoDimensionSel(this)"></span>';

	            return t;
	        }

	        /**
	         * 自定义尺码编辑生成函数
	         * @param value
	         * @param options
	         * @returns {string}
	         */
	        function sizeElement(value, options) {

	            var t = '<input type="text" placeholder="点击选择" readonly onfocus="showAutoSizes(this)" class="textbox goodsAuto" value="'+value+'" ><span class="ui-icon-triangle-1-s"></span>';

	            return t;
	        }

	        /**
	         * 自定义颜色编辑生成函数
	         * @param value
	         * @param options
	         * @returns {string}
	         */
	        function colorElement(value, options) {

	            var t = '<input type="text" placeholder="点击选择" readonly onfocus="showAutoColors(this)" class="textbox goodsAuto" value="'+value+'" ><span class="ui-icon-triangle-1-s"></span>';

	            return t;
	        }
	        
	        /**
	         * 自定义单价编辑生成函数
	         * @param value
	         * @param options
	         * @returns {string}
	         */
	        function priceElement(value, options) {
	        	var t = '<input type="text" placeholder="0.00" onfocus ="showAutoPrices(this)" class="textbox goodsAuto" value="'+value+'" ><span class="ui-icon-triangle-1-s"></span>';
	            return t;
	        }
	        
	        /**
	         * 自定义折后价编辑生成函数
	         * @param value
	         * @param options
	         * @returns {string}
	         */
	        function truePriceElement(value, options) {
	        	var t = '<input type="text" placeholder="0.00" onfocus ="showAutoTruePrices(this)" class="textbox goodsAuto" value="'+value+'" ><span class="ui-icon-triangle-1-s"></span>';
	        	return t;
	        }

	        
	        /**
	         * 自定义商品选择好后返回表格的值
	         * @param elem
	         * @param operation
	         * @param value
	         * @returns {*|jQuery}
	         */
	        function goodsValue(elem, operation, value) {
	            if(operation === 'get') {

	                return $(elem).val();
	            } else if(operation === 'set') {
	                $(elem).val(value);
	            }
	        }

	        /**
	         * 自定义尺码选择好后返回到表格的值
	         * @param elem
	         * @param operation
	         * @param value
	         * @returns {*|jQuery}
	         */
	        function sizeValue(elem, operation, value) {
	                if(operation === 'get') {

	                    return $(elem).val();
	                } else if(operation === 'set') {
	                    $(elem).val(value);
	                }
	        }

	        /**
	         * 自定义颜色选择好后返回到表格的值
	         * @param elem
	         * @param operation
	         * @param value
	         * @returns {*|jQuery}
	         */
	        function colorValue(elem, operation, value) {
	            if(operation === 'get') {

	                return $(elem).val();
	            } else if(operation === 'set') {
	                $(elem).val(value);
	            }
	        }
	        
	        /**
	         * 自定义单位选择好后返回到表格的值
	         * @param elem
	         * @param operation
	         * @param value
	         * @returns {*|jQuery}
	         */
	        function priceValue(elem, operation, value) {
	                if(operation === 'get') {
	                	var returnValue = "";
	                	if($(elem).val() || $(elem).val()===0){
	                		returnValue = $(elem).val();
	                	}
	                	hideAutoPrices();
	                	return returnValue;
	                } else if(operation === 'set') {
	                    $(elem).val(value);
	                }
	        }
	        
	        /**
	         * 自定义单位选择好后返回到表格的值
	         * @param elem
	         * @param operation
	         * @param value
	         * @returns {*|jQuery}
	         */
	        function truePriceValue(elem, operation, value) {
	        	if(operation === 'get') {
	        		var returnValue = "";
                	if($(elem).val() || $(elem).val()===0){
                		returnValue = $(elem).val();
                	}
                	hideAutoTruePrices();
                	return returnValue;
	        	} else if(operation === 'set') {
	        		$(elem).val(value);
	        	}
	        }

	        /**
	         * 点击单元格开始进行编辑事件
	         * @param rowid
	         * @param cellname
	         * @param value
	         * @param iRow
	         * @param iCol
	         */
	        function beforeEditCell(rowid, cellname, value, iRow, iCol)
	        {
	            lastrow =  iRow;        //全局变量，记录准备编辑的行
	            lastcell =  iCol;       //全局变量，记录准备编辑的列
	            
	            getScope('OrderCtrl').$apply(function(scope){
	    	        scope.showAutoGoods = false;
	    	        scope.showAutoSize = false;
	    	        scope.showAutoColor = false;
	    	        scope.showAutoPrice = false;
	    	        scope.showAutoTruePrice = false;
	    	    });
	        }

	        function afterEditCell (rowid, cellname, value, iRow, iCol)
	        {
	        	 setTimeout(function() {$("#"+iRow+"_"+cellname).focus().val(value);});
	            //$("#"+iRow+"_"+cellname).focus();                     //聚焦被覆盖，这个地方需要修改
	            //$(".textbox.goodsAuto.customelement")[0].focus();     //聚焦被覆盖，这个地方需要修改

	        }

	        function beforeSaveCell (rowid, cellname, value, iRow, iCol)
	        {
	        	/*calcTotal('amount');
	        	calcTotal('trueAmount');*/
	        }

	        function afterRestoreCell (rowid, value, iRow, iCol)
	        {
	        	
				var ctrlScope = getScope('OrderCtrl');
				

				setTimeout(function(){
							ctrlScope.$apply(function(scope) {
								scope.showAutoGoods = false;
								scope.showAutoSize = false;
								scope.showAutoColor = false;
								scope.showAutoPrice = false;
								scope.showAutoTruePrice = false;
							});
						});
	        }
	        
	        /**
	         * 在每个表格调用之后事件函数，进行自动填充，金额计算等工作
	         * @param rowid
	         * @param cellname
	         * @param value
	         * @param iRow
	         * @param iCol
	         */
	        function afterSaveCell(rowid, cellname, value, iRow, iCol) {
	        	var scope = getScope('OrderCtrl');
	        	scope.notSaveOrder = true;
	        	var currentRowData = $("#list4").jqGrid("getRowData",rowid);
	            if (cellname == "goodName") {
                    // temp =  scope.curEditGoodInput.val();
                    var good = scope.selGood;
                    if(good == undefined)
                    {
                        $("#list4").setRowData(rowid, {goodName:"",sizeName:"", colorName:"", goodsSn:"",price: "", amount: "",trueAmount: "" });
                        return ;
                    }
                    var discount = currentRowData['discount'];
                    
                    $("#list4").setRowData(rowid, {
						unit : good.unit,
						quantity : 1,
						price : good.factoryPrice,
						truePrice: setScale(accDiv(accMul(good.factoryPrice,discount),100),2),
						amount : good.factoryPrice,
						trueAmount: setScale(accDiv(accMul(good.factoryPrice,discount),100),2),
						sizeIds : good.sizeIds,
						colorIds : good.colorIds,
						goodsSn : good.goodsSn,
						discount:discount
					});
                    
                    
                    scope.selGood = undefined;
                    //  $("#list4").setRowData( rowid, { unit:1, quantity:1,price:1,amount:1 });
	            }
	            else if (cellname == "sizeName") {
            		
            		var rowIds = jQuery("#list4").jqGrid('getDataIDs'); //获取所有行Id
	    			var existsSameFlag = false;
	    	        for (var j = 0; j < rowIds.length; j++) {
	    	        	var thisRow = $("#list4").jqGrid("getRowData",rowIds[j]); //当前行数据
	    	        	if(thisRow['goodsSn'] == currentRowData['goodsSn'] && thisRow['colorId'] == currentRowData['colorId'] && thisRow['sizeId'] == scope.selSize.id){
	    	        		if(thisRow['id'] == rowid){
	    	        			continue;
	    	        		}else{
	    	        			var r = confirm("已经存在相同颜色尺码的商品，是否合并数量为一条记录？");
	    	        			if(r){
	    	        				$("#list4").setRowData(rowIds[j], {
										packetCount : parseInt(thisRow['packetCount']) + parseInt(currentRowData['packetCount']),
										packetNumber : parseInt(thisRow['packetNumber']),
										quantity : accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity']),
			        					amount : accMul((accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])),thisRow['price']),
			        					trueAmount: accMul((accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])),thisRow['truePrice']) 
									});
	    	        				$("#list4").jqGrid("delRowData", rowid);
	    	        			}else{
	    	        				$("#list4").setRowData(rowid, {  sizeId:'',sizeName:'',number:''});
	    	        			};
	    	        			existsSameFlag = true;
		    	        		break;
	    	        		}
	    	        	}
	    	        }
            		
            		if(!existsSameFlag){
            			$("#list4").setRowData(rowid, {  sizeId:scope.selSize.id});
            			currentRowData.sizeId = scope.selSize.id;
            			scope.updateRowDataForChangeSku(rowid, currentRowData);
                		scope.setGoodsStoredCount();
            		}
            	}
	            else if(cellname == "colorName")
	            {
                	if(scope.selColor!= undefined)
                	{
                		var rowIds = jQuery("#list4").jqGrid('getDataIDs'); //获取所有行Id
    	    			var existsSameFlag = false;
    	    	        for (var j = 0; j < rowIds.length; j++) {
    	    	        	var thisRow = $("#list4").jqGrid("getRowData",rowIds[j]); //当前行数据
    	    	        	if(thisRow['goodsSn'] == currentRowData['goodsSn'] && thisRow['colorId'] ==  scope.selColor.id && thisRow['sizeId'] == currentRowData['sizeId']){
    	    	        		if(thisRow['id'] == rowid){
    	    	        			continue;
    	    	        		}else{
    	    	        			var r = confirm("已经存在相同颜色尺码的商品，是否合并数量为一条记录？");
    	    	        			if(r){
    	    	        				$("#list4").setRowData(rowIds[j], {
											packetCount : parseInt(thisRow['packetCount']) + parseInt(currentRowData['packetCount']),
											packetNumber : parseInt(thisRow['packetNumber']),
											quantity : accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity']),
				        					amount : accMul((accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])),thisRow['price']),
				        					trueAmount: accMul((accMul(parseInt(thisRow['packetCount']),currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])),thisRow['truePrice']) 
										});
    	    	        				$("#list4").jqGrid("delRowData", rowid);
    	    	        			}else{
    	    	        				$("#list4").setRowData(rowid, {colorId:'',colorName:'',number:''});
    	    	        			};
    	    	        			existsSameFlag = true;
    		    	        		break;
    	    	        		}
    	    	        	}
    	    	        }
                		if(!existsSameFlag){
                			$("#list4").setRowData(rowid, {  colorId:scope.selColor.id});
                			currentRowData.colorId = scope.selColor.id;
                			scope.updateRowDataForChangeSku(rowid, currentRowData);
                			scope.setGoodsStoredCount();
                		}
                	}
	            }
	            else if (cellname == "packetCount") {
	                if(value<1)
	                {
	                    value = 1;
	                    $("#list4").setRowData(rowid, {  quantity:1 });
	                }
	                
	                /*if(parseInt(rowData['number']) - parseInt(value) < 0 ){
	            		alert("请注意：该类商品库存不足！");
	            	}*/
	                
	                $("#list4").setRowData(rowid, {  amount: accMul(accMul(currentRowData['packetNumber'],value),currentRowData['price']),trueAmount: accMul(accMul(currentRowData['packetNumber'],value),currentRowData['truePrice']),quantity: accMul(currentRowData['packetNumber'],value)});
	            }else if (cellname == "price") {
	            	$("#list4").setRowData(rowid, {  truePrice: setScale(accDiv(accMul(currentRowData['price'],currentRowData['discount']),100),2) });
	            	$("#list4").setRowData(rowid, {  amount: accMul(currentRowData['quantity'],currentRowData['price']),trueAmount: accMul(setScale(accDiv(accMul(currentRowData['price'],currentRowData['discount']),100),2),currentRowData['quantity']) });
	            }else if (cellname == "discount") {
	                if(value<0)
	                {
	                    value = 100;
	                    $("#list4").setRowData(rowid, {  discount:100 });
	                }
	                $("#list4").setRowData(rowid, {  truePrice: setScale(accDiv(accMul(currentRowData['price'],currentRowData['discount']),100),2) });
	                $("#list4").setRowData(rowid, {  trueAmount: accMul(currentRowData['quantity'],setScale(accDiv(accMul(currentRowData['price'],currentRowData['discount']),100),2)) });
	            }else if(cellname = "truePrice"){
	            	if(currentRowData['price'] == 0){
	            		$("#list4").setRowData(rowid, {  discount: 100 });
	            		value = 0;
	            	}else {
	            		$("#list4").setRowData(rowid, {  discount:setScale(accDiv(accMul(currentRowData['truePrice'],100),currentRowData['price']),2) });
	            	}
	            	$("#list4").setRowData(rowid, {  trueAmount: accMul(currentRowData['truePrice'],currentRowData['quantity']) });
	            }
	            
	            //更新合计行上的合计指标
    	        updateTotalNumbers();

	            setTimeout(function(){	
	   				 scope.$apply(function(scope){
	   					if(scope.businessConfig.zeroPaid == 1){
	  						scope.order.alreadyPaid = 0;
	  					}else{
	  						scope.order.alreadyPaid = scope.order.finalTotalAmount;
	  					}
	   		    	});
	   			 });
	        }

	        jQuery("#list4").jqGrid(
	            {
	            	cmTemplate:{sortable:false},
	                datatype : "local",
	                cellEdit: true,
	                cellsubmit:'clientArray',
	                colModel : [
	                 {name:'operate', index:'operate',label: "操作",formatter:pubBillsOper,align: "center",width: 70,fixed: true,resizable:false},
	                {
	                	 hidden: true,
	                    name : 'id',
	                    index : 'id'
	                }, {
	                	hidden: true,
	                    name : 'itemType',
	                    index : 'itemType'
	                },{
	                    hidden: true,
	                    name : 'sizeIds',
	                    index : 'sizeIds',
	                    label: "商品尺码串"
	                },{
	                    hidden: true,
	                    name : 'sizeId',
	                    index : 'sizeId',
	                    label: "商品尺码"
	                },{
	                    hidden: true,
	                    name : 'colorIds',
	                    index : 'colorIds',
	                    label: "颜色串"
	                },{
	                    hidden: true,
	                    name : 'colorId',
	                    index : 'colorId',
	                    label: "颜色串"
	                },
	                {
	                    name : 'goodName',
	                    index : 'goodName',
	                    label: "商品",
	                    sortable:true,
	                    formatter: editableColumnTip,
	                    unformat: editableColumnRemoveTip,
	                    width: 300, classes: "ui-ellipsis",  editable: true,edittype: "custom",editrules:{ required:false}, editoptions: {custom_element: goodElement, custom_value: goodsValue,  trigger: "ui-icon-ellipsis"}
	                },{
	                    hidden: true,
	                    name : 'name',
	                    index : 'name',
	                    label: "名称"
	                }, {
	                    name : 'goodsSn',
	                    index : 'goodsSn',
	                    label: "货号",
	                    sortable:true
	                },{
	                    name : 'barCode',
	                    index : 'barCode',
	                    label: "条码",
	                    align:"center",
	                    width:190
	                },
	                {
	                    name : 'colorName',
	                    index : 'colorName' ,
	                    label: "颜色"  ,
	                    align:"center",
	                    sortable:true,
	                    classes: "ui-ellipsis cell-can-edit", editable: true,edittype: "custom",  editoptions: {custom_element: colorElement, custom_value: colorValue}
	                }, {
	                    name : 'sizeName',
	                    index : 'sizeName',
	                    label: "尺码" ,
	                    align:"center",
	                    classes: "ui-ellipsis cell-can-edit", editable: true,edittype: "custom",  editoptions: {custom_element: sizeElement, custom_value: sizeValue,  trigger: "ui-icon-ellipsis"}
	                }, {
	                    name : 'unit',
	                    index : 'unit',
	                    label: "单位",
	                    width:65,
	                    align:"center"
	                },{
	                    name : 'quantity',
	                    index : 'quantity',
	                    hidden : true
	                }, {
	                    name : 'packetCount',
	                    index : 'packetCount',
	                    label: "数" ,
	                    align:"right",
	                    width:155,
	                    editable: true  ,
	                    formatter: 'integer'  ,
	                    classes: "ui-ellipsis cell-can-edit",
	                    editrules:{
	                    	custom:true,
	                    	custom_func: function(value){
	                    		var packetCount = parseInt(value);
	                    		var isValid = !isNaN(packetCount);
	                    		var isInteger = value % 1 == 0;
	                    		if(!isValid || !isInteger){
	                    			return [false, '请输入有效整数'];
	                    		}
	                    		if(packetCount == 0){
	                    			return [false, '商品数量不能为0'];
	                    		}
	                    		return [true,''];
	                    	}
	                    },
		                editoptions: {
	                    	dataEvents:[
	                    	   {type: 'focus',fn: function(e) {
	                    		   setTimeout(function() {$(e.target).select();}, 50);
	                    	   }}
	                    	]
	                	}
	                }, {
	                	name : 'packetNumber',
	                    index : 'packetNumber',
	                    label : "量",
	                    align:"left",
	                    width:45,
	                    formatter: function(val, opt, row) {
	                    	if(val == 1 || !val){
	                    		return '';
	                    	}
	                    	return '×'+val;
	                    },
	                	unformat : function(val, opt, row) {
	                    	if(!val){
	                    		return 1;
	                    	}
	                    	return parseInt(val.substring(1));
	                    }
	                }, {
	                	name : 'price',
	                    index : 'price',
	                    align:"right",
	                    label: "单价", sorttype: "float", formatter: 'currency',
	                    editable: true ,
	                    editrules:{minValue:0,number:true},
	                    classes: "ui-ellipsis cell-can-edit", edittype: "custom",  
	                	editoptions: {custom_element: priceElement, custom_value: priceValue,
	                		dataEvents:[
	     	                    	   {type: 'focus',fn: function(e) {
	     	                    		   setTimeout(function() {$(e.target).select();}, 50);
	     	                    	   }}
	     	                    	]
	                    }
	                }, {
	                    name : 'discount',
	                    index : 'discount',
	                    label: "折扣(%)",
	                    editable: true ,
	                    classes: "ui-ellipsis cell-can-edit",
	                    align:"right",
	                    defaultValue:100,
	                    formatter:discount,
	                    editrules:{minValue:0,number:true},
		                editoptions: {
	                    	dataEvents:[
	                    	   {type: 'focus',fn: function(e) {
	                    		   setTimeout(function() {$(e.target).select();}, 50);
	                    	   }}
	                    	]
	                	}
	                }, {
	                	name : 'truePrice',
	                    index : 'truePrice',
	                    align:"right",
	                    label: "折后价", sorttype: "float", formatter: 'currency',
	                    editable: true ,
	                    editrules:{minValue:0,number:true},
	                    classes: "ui-ellipsis cell-can-edit", edittype: "custom",  
	                    editoptions: {custom_element: truePriceElement, custom_value: truePriceValue,
	                		dataEvents:[
		     	                    	   {type: 'focus',fn: function(e) {
		     	                    		   setTimeout(function() {$(e.target).select();}, 50);
		     	                    	   }}
		     	                    	]
	                    }
	                },{
	                    name : 'factoryPrice',
	                    index : 'factoryPrice',
	                    hidden:true,
	                    label: "采购价"
	                },{
	                    name : 'supplierPrice',
	                    index : 'supplierPrice',
	                    hidden:true,
	                    label: "供应商上次价格"
	                },{
	                    name : 'supplierTruePrice',
	                    index : 'supplierTruePrice',
	                    hidden:true,
	                    label: "供应商上次折后价格"
	                },{
	                	hidden: true,
	                    name : 'number',
	                    index : 'number',
	                    label: "当前数量",
	                    align:"right",
	                    formatter: 'integer' 
	                }, {
	                    name : 'amount',
	                    index : 'amount',
	                    label: "金额" ,
	                    align:"right",
	                        sorttype: "float", formatter: 'currency'
	                },{
	                    name : 'trueAmount',
	                    index : 'trueAmount',
	                    label: "折后金额" ,
	                    align:"right",
	                    sorttype: "float", formatter: 'currency'
	                }   ],
	                multiSort:true,
	                rownumbers : true, //	--是否在表格最前端添加1列为自动编号
	                rownumWidth:35,
	                rowNum : 1000, //       --一页显示几行？
	                page : 1, //    --从弟几页开始
	                rowlist : [ 10, 20, 30 ], //    --多少页一段
	                height : "100%",
	                width : "100%",
	                footerrow: true ,
	                autowidth:true,
	                afterSaveCell:afterSaveCell ,
	                beforeEditCell:beforeEditCell,
	                afterEditCell:afterEditCell,
	                beforeSaveCell:beforeSaveCell,
	                afterRestoreCell:afterRestoreCell,
	                oneditfunc: function() {
	                   // alert ("edited");
	                },
	                loadComplete: function () {
	                	 //更新合计行上的合计指标
	        	        updateTotalNumbers();
	            }
	                , loadGrid: function (t) {
	                function e(t) {

	                }
	            }

	            }).jqGrid('navGrid', "#pager", {
	                refresh : true,
	                add : true,
	                edit : true,
	                del : true,
	                search : false,
	                sortable : false

	                // (3) 点击删除按钮，则调用openDialog4Deleting方法
	            }, {
	                closeOnEscape : true,
	                closeAfterEdit : true
	            }, {
	                closeOnEscape : true,
	                closeAfterAdd : true,
	                serializeEditData : function(data) {
	                    return $.param($.extend({}, data, {
	                        id : ''
	                    }));
	                }
	            });
	        jQuery("#list4").trigger("reloadGrid");

	        
	        for ( var i = 0; i <= 5; i++) {
	            addNewEmptyRow();

	        }

	        //修复排序列表头样式
			var myGrid = $("#list4");
			var cm = myGrid[0].p.colModel;
			$.each(myGrid[0].grid.headers, function(index, value) {
			    var cmi = cm[index], colName = cmi.name;
			    if(cmi.sortable && colName!=='rn' && colName!=='cb' && colName!=='subgrid') {
			        $('div.ui-jqgrid-sortable',value.el).addClass('sortable');
			        $('div.ui-jqgrid-sortable',value.el).prepend('<span class="sortable-icon"></span>');
			    }
			});
	        
	        //自适应宽度
	        $(window).resize(function(){
	        	//在resize过程中宽度为0时不应设置
				if ($("#list4").parent().parent().parent().parent().parent().width() != 0) {
					$("#list4").setGridWidth($("#list4").parent().parent().parent().parent().parent().width());
				}
	    		$("#listGrid").setGridWidth($("#listGrid").parent().parent().parent().parent().parent().width());
	    	});

	      //初始化二维录入弹框
	    	$( "#twoDisDiv" ).dialog({
	    	    autoOpen: false,
	    	    show: {
	    	      effect: "blind",
	    	      duration: 10
	    	    },
	    	   minWidth: 800,
	    	   modal: true
	    	   
	    	});
	    	
	    	//初始化打印模板选择窗口
	    	$( "#printTemplateListDiv" ).dialog({
	    		autoOpen: false,
	    		show: {
	    			effect: "blind",
	    			duration: 10
	    		},
	    		position:['middle',150],
	    		minWidth: 800,
	    		modal: true,
	    		title: "选择打印模板"	    		
	    	});
	    	
	    
    	//判断是否加载订单
    	if(onLoadOrdersSn != null && onLoadOrdersSn != undefined&& onLoadOrdersSn != '')
    	{
    		getScope('OrderCtrl').loadOneOrder(onLoadOrdersSn);
    	};
    	
    	//设置jqgrid表头对齐方式
	   	 $("#list4").jqGrid("setLabel","goodName","",{"text-align":"left"});
	   	 $("#list4").jqGrid("setLabel","goodsSn","",{"text-align":"left"});
	   	 $("#list4").jqGrid("setLabel","quantity","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","packetCount","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","packetNumber","",{"text-align":"left"});
	   	 $("#list4").jqGrid("setLabel","price","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","truePrice","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","discount","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","amount","",{"text-align":"right"});
	   	 $("#list4").jqGrid("setLabel","trueAmount","",{"text-align":"right"});
	   	 
	   	 // 销售单转采购单
	   	 getWholesaleOrders(wholesaleOrdersSn);
    	
	   	leavePage([{test:"getScope('OrderCtrl').notSaveOrder",info:"亲，单据还没有保存哦！"}]);
	   	
	   	$(window).resize();
	   	
	    });

	/**
	 *   添加空的新行
	 * @param position   插入的位置（first：表格顶端；last：表格底端；before：srcrowid之前；after：srcrowid之后）；
	 * @param srcrowid   新行将插入到srcrowid指定行的前面或后面
	 * @returns {number}返回新rowId
	 */
	function addNewEmptyRow(position ,srcrowid )
	{
	    if(maxRowId == undefined)
	    {
	        maxRowId = jQuery("#list4").jqGrid('getDataIDs').length;
	    }
	    maxRowId = maxRowId+1;
	    var data = {
	        id : maxRowId,
	        goodName : "",
	        colorName : "",
	        sizeName : "",
	        unit : "",
	        price : "",
	        quantity : 1,
	        packetCount: 1,
	        packetNumber: 1,
	        number: "",
	        amount : "",
	        trueAmount : "",
	        discount:getScope('OrderCtrl').supplierDiscount
	    };
	    $('#list4').jqGrid('addRowData', maxRowId,data,position ,srcrowid);
	    return maxRowId;
	}

	/**
	 * 监听表格中的键盘事件
	 */
	jQuery(document).delegate('.ui-jqgrid','keydown', function(event){
	    var key = event.charCode || event.keyCode;
	    if(key == 9)
	    {
	        var selRowId= $('#list4').jqGrid('getGridParam','selrow');
	        var arrIds = jQuery("#list4").jqGrid('getDataIDs');

	        if(selRowId == arrIds[arrIds.length - 1])
	        {
	            var newRowId = addNewEmptyRow();
	            $('#list4').editCell( newRowId, 8, true);      //设置最新行被选中
	        }

	    }

	});

	/**
	 * 在当前行下插入空行
	 * @param rowId
	 */
	function insertEmptyRow(event,srcRowId){
		stopEvent(event);

	    $("#list4").jqGrid("saveCell",lastrow,lastcell);
	   // $('#list4').editCell( lastrow,lastcell, false);      //设置最新行被选中
	    $('#list4').jqGrid('resetSelection');
	 //   $("#list4").saveRow(lastrow);

	    var newRowId = addNewEmptyRow('after',srcRowId);

	    //var newRowId = addNewEmptyRow('after',3);
	    var iRow = $('#' + $.jgrid.jqID(newRowId))[0].rowIndex;
	      $('#list4').editCell(iRow, 8, true);      //设置最新行被选中
	    //$( "#list4" ).resetSelection();
	};

	function delRow(event,rowId)
	{
		stopEvent(event);
	    if($("#list4").jqGrid("getRowData").length == 1){ //只剩一行时，不允许删除
	    	return;
	    }
	    if($("#list4").getRowData(rowId).goodName){
	    	getScope('OrderCtrl').notSaveOrder = true;
	    }
	    $("#list4").jqGrid("saveCell",lastrow,lastcell);
	    
	    var currentRowData = $('#list4').jqGrid('getRowData', rowId);
	    var flag = false;
	    $("#list4").jqGrid("delRowData", rowId);
	    var allRows = $("#list4").jqGrid("getRowData");
	    for(var i = 0; i < allRows.length; i++){
	    	if(currentRowData['goodsSn'] == allRows[i]['goodsSn']){
	    		flag = true;
	    		break;
	    	}
	    }
	    if(!flag){
	    	for(var i = 0; i < getScope('OrderCtrl').snPacketArr.length; i++){
	    		//只循环一次
	    		for(var snPacket in getScope('OrderCtrl').snPacketArr[i]){
	    			if(snPacket == currentRowData['goodsSn']){
	    				getScope('OrderCtrl').snPacketArr.splice(i, 1);
	    			}
	    		}
	    	}
	    }
	    //更新合计行上的合计指标
        updateTotalNumbers();
	    setTimeout(function(){
	    	getScope('OrderCtrl').$apply(function(scope){
	    		if(scope.businessConfig.zeroPaid == 1){
	    			scope.order.alreadyPaid = 0;
	    		}else{
	    			scope.order.alreadyPaid = scope.order.finalTotalAmount;
	    		}
	    	});
		 });
	}

	/**
	 * 合计商品列表中某些列的数值，不包括货号列为空的行
	 * @returns 返回包括各个传入列合计值的对象，如{totalAvailableRows:120,quatity:98,amount:102}, 
	 * 			其中totalAvailableRows为内置变量，用以表示商品不为空的行数
	 */
	function calcTotal()
	{
		var allRowData = $("#list4").jqGrid("getRowData");
		
		var result = {};
		for(var i = 0;i < arguments.length;i++){
			result[arguments[i]] = 0;
		}
		result['totalAvailableRows'] = 0;
		for(var i = 0;i < allRowData.length;i++){
			var currentRowData = allRowData[i];
			if(currentRowData['goodName']){
				for(var j = 0;j < arguments.length;j++){
					result[arguments[j]] = accAdd(result[arguments[j]],currentRowData[arguments[j]]);
				}
				
				result['totalAvailableRows'] = result['totalAvailableRows'] + 1;
			}
		}
		return result;
	}
	
	/**
	 * 更新商品单据的合计值
	 */
	 function updateTotalNumbers(){
	 	//更新合计行上的合计指标
        var totalObj = calcTotal('quantity','amount','trueAmount');
        $("#list4").footerData("set",$.extend({goodName:"合计",packetCount:totalObj.quantity},totalObj));
        
        //更新应收合计等合计指标
        var scope = getScope('OrderCtrl');
        scope.order.totalAmount = totalObj.amount;
        scope.order.trueTotalAmount = totalObj.trueAmount;
        scope.order.finalTotalAmount = accAdd(accSub(scope.order.trueTotalAmount,scope.order.wipeZero),scope.order.otherCost);
        scope.order.totalAvailableRows = totalObj.totalAvailableRows;
        
	 }
	
	/**
	 * 点击商品列时，如果输入为空，显示商品下拉框
	 * @param obj
	 */
	function loadGoodsFirst(obj)
	{
		getScope("OrderCtrl").barCodeFocus = false;
		if( $(obj).val() == ''){
			var ctrl = angular.element(document.getElementById('OrderCtrl'));
			var ctrlScope = ctrl.scope();
			ctrlScope.$apply(function(scope){
				scope.changAutoGoods( obj);  //重新加载商品并显示下拉框
				scope.searchGoodAct = -1; //商品查询下拉选中项
			});
		}
		setTimeout(function() {obj.select();}, 50);
	}
	
	// 500毫秒后查询匹配的商品
	var vCheckGoodsTimeOut = undefined;

	/**
	 * 显示商品下拉框
	 * @param obj
	 */
	function changAutoGoods(obj)
	{
	    var ctrl = angular.element(document.getElementById('OrderCtrl'));
	    var ctrlScope = ctrl.scope();
		if(vCheckGoodsTimeOut){
			window.clearTimeout(vCheckGoodsTimeOut);
		}
		// 500毫秒内如果有改动查询关键字，就取消查询，否则触发查询。
		vCheckGoodsTimeOut = setTimeout(function() {
			ctrlScope.$apply(function(scope){
		    	scope.changAutoGoods( obj);  //重新加载商品并显示下拉框
		    	scope.searchGoodAct = -1; //商品查询下拉选中项
		    });
		}, 500);
	}
	
	/**
	 * 显示商品下拉框,兼容IE(ie9商品输入框中删除输入字符时不会触发onpropertychange事件)
	 * @param obj
	 */
	function changAutoGoodsIE(event)
	{
		 if (event.propertyName.toLowerCase () == "value") {
			 var ctrl = angular.element(document.getElementById('OrderCtrl'));
			    var ctrlScope = ctrl.scope();
			    var vElement = event.srcElement;
			    if(vCheckGoodsTimeOut){
					window.clearTimeout(vCheckGoodsTimeOut);
				}
			    // 500毫秒内如果有改动查询关键字，就取消查询，否则触发查询。
				vCheckGoodsTimeOut = window.setTimeout(function() {
					ctrlScope.$apply(function(scope){
						scope.changAutoGoods(vElement);  //重新加载商品并显示下拉框
						scope.searchGoodAct = -1; //商品查询下拉选中项
					});
				}, 500);
         }
	}
	
	/**
	 * 商品查询中按下键盘事件
	 */
	function goodsSearchPress(keyEvent,obj)
	{
		getScope('OrderCtrl').rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
		 var keyCode = keyEvent.which;
		 
         switch(keyCode)
         {
        
             case 38: //up
            	 goodsSearchCtrlUp(keyEvent);
                 break;
             case 40: //down
                 goodsSearchCtrlDown(keyEvent);
                 break;
             case 13: //Enter
            	 goodsSearchCtrlEnter(keyEvent);
            	 break;
             default:

         }
		
	}
	
	/**
	 * 处理商品查询中按下键盘事件,向上键
	 */
	function goodsSearchCtrlUp(keyEvent)
	{
		getScope('OrderCtrl').$apply(function(scope){
			if(scope.searchGoodAct>0)
			{
				scope.searchGoodAct--; //当前行id
			}
	        
	    });
	}
	/**
	 * 处理商品查询中按下键盘事件,向下键
	 */
	function goodsSearchCtrlDown(keyEvent)
	{
		getScope('OrderCtrl').$apply(function(scope){
			if(scope.searchGoodAct<scope.goods.length-1)
			{
				scope.searchGoodAct++; //当前行id
			}
		});
	}
	/**
	 * 处理商品查询中按下键盘事件,Enter键
	 */
	function goodsSearchCtrlEnter(keyEvent)
	{
		getScope('OrderCtrl').$apply(function(scope){
			if(scope.searchGoodAct>-1 && scope.searchGoodAct<scope.goods.length)
			{
				scope.selAutoGood(scope.goods[scope.searchGoodAct]);
				scope.searchGoodAct=-1;//处理完后初始化为-1
			}
		});
	}

	/**
	 * 处理并显示二维录入框，点输入框内单品后三个点(详情)触发
	 * 直接重新搜索商品不会触发此处
	 */
	function showTwoDimensionSel(obj)
	{
		getScope('OrderCtrl').$apply(function(scope){
			scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
	        
	        scope.currentRowData = $('#list4').jqGrid('getRowData', scope.rowId ); //行数据
	        scope.initPacketNumber(scope.currentRowData.goodsSn, scope.currentRowData.packetNumber);
			scope.showAndProTwoDimensionSel(scope.currentRowData);
	    });
	}
	
	/**
	 * 显示尺码的下拉框
	 * @param obj
	 */
	function showAutoSizes(obj)
	{

	    getScope('OrderCtrl').$apply(function(scope){
	        scope.currentSizes = [];   //当前商品所拥有的尺码
	        scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
	        var rowData = $('#list4').jqGrid('getRowData', scope.rowId ); //行数据

	        var curGoodSn =rowData['goodsSn']; //行货号
	        if(curGoodSn == undefined || curGoodSn == "")
	        {
	            return;
	        }
	        scope.currentSizes = idStringToObjectArray(scope.allSizes, rowData['sizeIds'], 'id', ',');

	        scope.showAutoSize = true;
	        
	        var offset = jQuery(obj).offset(); 
	        var top = (offset.top + jQuery(obj).outerHeight())+'px';
	        var width = (jQuery(obj).width()+18)+'px';
	        var left = (offset.left)+'px';
	        scope.autoSizStyle =  { top: top, width:width, left: left};
	        scope.curEditSizeInput = $(obj);       //指向当前编辑的表格
	    });
	}

	/**
	 * 显示颜色的下拉框
	 * @param obj
	 */
	function showAutoColors(obj)
	{
	    getScope('OrderCtrl').$apply(function(scope){
	        scope.currentSizes = [];   //当前商品所拥有的尺码
	        scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
	        var rowData = $('#list4').jqGrid('getRowData', scope.rowId ); //行数据

	        var curGoodSn =rowData['goodsSn']; //行货号
	        if(curGoodSn == undefined || curGoodSn == "")
	        {
	            return;
	        }
	        scope.currentColors = idStringToObjectArray(scope.allColors, rowData['colorIds'], 'id', ',');

	        scope.showAutoColor = true;
	        var offset = jQuery(obj).offset(); 
	        var top = (offset.top + jQuery(obj).outerHeight())+'px';
	        var width = (jQuery(obj).width()+18)+'px';
	        var left = (offset.left)+'px';
	        scope.autoColorStyle =  { top: top, width:width, left: left};
	        
	        scope.curEditColorInput = $(obj);       //指向当前编辑的表格
	    });
	}
	
	
	
	/**
	 * 显示单价的下拉框
	 * @param obj
	 */
	function showAutoPrices(obj)
	{
		getScope('OrderCtrl').$apply(function(scope){
			scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
			var rowData = $('#list4').jqGrid('getRowData', scope.rowId ); //行数据
			scope.currentPrices=[];
			
			if(rowData['factoryPrice'] || rowData['factoryPrice'] === 0){
				scope.currentPrices.push({text:'采购价',value:setScaleToFixed(rowData['factoryPrice'],2)});
			}
			
			if(rowData['supplierPrice'] || rowData['supplierPrice'] === 0){
				scope.currentPrices.push({text:'上次单价',value:setScaleToFixed(rowData['supplierPrice'],2)});
			}
			
			if(scope.currentPrices.length>0){
				scope.showAutoPrice = true;
				var offset = jQuery(obj).offset(); 
				var top = (offset.top + jQuery(obj).outerHeight())+'px';
				var width = (jQuery(obj).width()+18)+'px';
				var left = (offset.left)+'px';
				scope.autoPriceStyle =  { top: top,'min-width':width, left: left};
				
				scope.curEditPriceInput = $(obj);       //指向当前编辑的表格
			}
		});
		setTimeout(function() {obj.select();}, 50);
	};
	
	/**
	 * 关闭单价的下拉框
	 */
	function hideAutoPrices()
	{
		getScope('OrderCtrl').$apply(function(scope){
			scope.showAutoPrice = false;
		});
	};
	
	/**
	 * 显示折后价的下拉框
	 * @param obj
	 */
	function showAutoTruePrices(obj)
	{
		getScope('OrderCtrl').$apply(function(scope){
			scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
			var rowData = $('#list4').jqGrid('getRowData', scope.rowId ); //行数据
			
			scope.currentTruePrices=[];
			if(rowData['supplierTruePrice'] || rowData['supplierTruePrice'] === 0){
				scope.currentTruePrices.push({text:'上次折后价',value:setScaleToFixed(rowData['supplierTruePrice'],2)});
			}
			
			if(scope.currentTruePrices.length>0){
				scope.showAutoTruePrice = true;
				var offset = jQuery(obj).offset(); 
				var top = (offset.top + jQuery(obj).outerHeight())+'px';
				var width = (jQuery(obj).width()+18)+'px';
				var left = (offset.left)+'px';
				scope.autoTruePriceStyle =  { top: top,'min-width':width, left: left};
				
				scope.curEditTruePriceInput = $(obj);       //指向当前编辑的表格
			}
		});
		setTimeout(function() {obj.select();}, 50);
	};
	
	/**
	 * 关闭折后价的下拉框
	 */
	function hideAutoTruePrices()
	{
		getScope('OrderCtrl').$apply(function(scope){
			scope.showAutoTruePrice = false;
		});
	}

	/**
	 *   点击表格之外
	 * @param e
	 */
	var lastrow;
	var lastcell;
	$('html').bind('click', function(e) { //用于点击其他地方保存正在编辑状态下的行
	    if ( lastrow != "" &&  lastcell != "") { //if a row is selected for edit
	        if($(e.target).closest('#list4').length == 0) { //and the click is outside of the grid //save the row being edited and unselect the row
	            // alert(lastsel);jQuery('#list4').jqGrid('restoreRow', lastsel);
	            // jQuery('#list4').resetSelection();
	            //$("#list4").jqGrid("restoreCell",lastrow,lastcell);

	            var ctrl = angular.element(document.getElementById('OrderCtrl'));
	            var ctrlScope = ctrl.scope();
	            ctrlScope.$apply(function(scope){
	            	scope.showAutoGoods = false;
	            	scope.showAutoSize = false;
	            	scope.showAutoColor = false;
	            	scope.showAutoPrice = false;
	            	scope.showAutoTruePrice = false;
	            });
	           $("#list4").jqGrid("saveCell",lastrow,lastcell);
	           lastrow = "";
	           lastcell = "";
	            setTimeout(function() {$(e.target).focus();}, 50); //由于保存表格语句会造成所点击的input失焦，所以需要臭不重新聚焦（需要重构）
	        }
	    }

});

/*回车事件*/
$('#searchForm').keypress(function(e) {
	if (e.keyCode == '13') {
		stopEvent(e);
		$('#searchBtn').click();
	}
});	

function getWholesaleOrders(wholesaleOrdersSn) {
	if(wholesaleOrdersSn){
   		var scope = getScope('OrderCtrl');
   		scope.notSaveOrder = true;
   		$.ajax({
   			url :  base + '/admin/inner/sale/toPurchaseOrderPage.ac?ordersSn='+wholesaleOrdersSn,
   			type : 'GET',
   			headers: {
   		        Accept: "application/json; charset=utf-8"
   		    },
   			beforeSend : function(){
   				scope.loadingTips = "加载中……";
   				scope.loadingOrder = true;
   			},
   			success : function(result){
   				var purchaseOrder = result;
		   		if(purchaseOrder.statusCode != 1) {
		   			alert(purchaseOrder.content);
		   			scope.loadingOrder = false;
		   			return ;
		   		}
		   		scope.editForm.$setPristine();//清除当前状态
		   		if(purchaseOrder.object.order){
		   			if(purchaseOrder.object.order.depotId){
		        		scope.order.depot = {val:purchaseOrder.object.order.depotId,text:purchaseOrder.object.order.depotName};
		        		scope.order.depotId = purchaseOrder.object.order.depotId;
		        		scope.order.depotName = purchaseOrder.object.order.depotName;
		        	}
		   			if(purchaseOrder.object.order.accountId){
		        		scope.selAccount = {val:purchaseOrder.object.order.accountId,text:purchaseOrder.object.order.accountName};
		        		scope.order.accountId = purchaseOrder.object.order.accountId;
		   			}
		   		}
				//更新商品表格
				jQuery("#list4").jqGrid("clearGridData");
				
				var goodsSnArr = [];
				
				if(maxRowId == undefined)
			    {
			        maxRowId = jQuery("#list4").jqGrid('getDataIDs').length;
			    }
				if(!purchaseOrder.object.orderGoods  || purchaseOrder.object.orderGoods.length ==0)  //如果还没有商品，则添加5个空行
				{
					for ( var i = 0; i <= 5; i++) {
			            addNewEmptyRow();
			        }
				}
				else
				{
					var snPacket = {};
		        	scope.resultOrderGoods = result.object.orderGoods;
					for(var i=0; i<purchaseOrder.object.orderGoods.length; i++)
			    	{
						goodsSnArr.push(purchaseOrder.object.orderGoods[i]['goodsSn']);
			    		maxRowId = maxRowId+1;
			    		var discountRes =  discount(purchaseOrder.object.orderGoods[i]['discount']);
			    		var factoryPrice = purchaseOrder.object.orderGoods[i]['factoryPrice'];
			    		purchaseOrder.object.orderGoods[i]['quantity'] = Math.abs(purchaseOrder.object.orderGoods[i]['quantity']);
			    		purchaseOrder.object.orderGoods[i]['goodName'] = purchaseOrder.object.orderGoods[i]['name'];
			    		purchaseOrder.object.orderGoods[i]['price'] = factoryPrice;
			    		purchaseOrder.object.orderGoods[i]['amount'] = accMul(factoryPrice,purchaseOrder.object.orderGoods[i]['quantity']);
			    		purchaseOrder.object.orderGoods[i]['truePrice'] = setScale(accDiv(accMul(factoryPrice,discountRes),100),2);
			    		purchaseOrder.object.orderGoods[i]['trueAmount'] = accMul(setScale(accDiv(accMul(factoryPrice,discountRes),100),2),purchaseOrder.object.orderGoods[i]['quantity']);
			    		purchaseOrder.object.orderGoods[i]['rowid'] = maxRowId;
			    		
			    		var flag = false;
			    		for(var sp in snPacket){
	            	    	if(sp == purchaseOrder.object.orderGoods[i]['goodsSn']){
	            	    		flag = true;
	            	    		break;
	            	    	}
	            	    }
	            	    if(!flag){
	            	    	snPacket[purchaseOrder.object.orderGoods[i]['goodsSn']] = purchaseOrder.object.orderGoods[i]['packetNumber'];
	            	    }
			    	}	
					scope.snPacketArr.push(snPacket);
			    	$('#list4').jqGrid('addRowData', "rowid", purchaseOrder.object.orderGoods);
				}
				scope.setOperation();
	        	if(scope.order.state == 1 && RESOURCES.indexOf("purchaseOrderEdit") != -1){
	        		scope.updateDiscount();
	        		if(goodsSnArr.length > 0 && scope.order.supplierId) {
	        			scope.updateSupplierPrice(scope.order.supplierId, goodsSnArr, scope.updateSupplierPriceByGoodsList, {});
	        		}
	        	}
	        	scope.loadingOrder = false;
   			},
   			error: function(result) {
   				alert(result.responseJSON.content);
	   			scope.loadingOrder = false;
	   			return ;
   			}
    	}
   	);}
}

/*打开滑动电子相册*/
var openGallery = function(){
	var scope = getScope('OrderCtrl');
	scope.$apply(function(){
		scope.initGallery()
	});
	$("#slideGallery").dialog("open");
};

/*关闭滑动电子相册*/
var closeGallery = function(){
	$("#slideGallery").dialog("close");
};

$("#slideGallery").dialog({
	autoOpen : false,
	show : {
		effect : "blind",
		duration : 10
	},
	position:['middle',100],
	width:754,
	height:504,
	modal : true,
	resizable : false,
	open : function() {
		
	},
	dialogClass:"slideGallery"
});